﻿Imports System.Data.SqlClient
Imports WindowsApplication1.IHMClass
Imports System.Text.RegularExpressions
Imports System.Net.Mail.MailMessage
Imports System.Windows.Shapes
Imports Word


Imports Excel

Module start
    Sub Main()
        Dim loginFormClass As New LoginForm
        If loginFormClass.getConnected() Then
            mainForm.currentUser = loginFormClass.getUser()
            mainForm.Text = mainForm.Text & " Login as " & mainForm.currentUser.getLogin()
            ' déactiver les fonctions selon la droit d'utilisateur
            Dim user As User = loginFormClass.getUser()
            If user.getUserRight() = 2 Then ' standard user
                With mainForm
                    .NewToolStripMenuItem.Enabled = False
                    .AlternatorToolStripMenuItem.Enabled = False
                    .StatorToolStripMenuItem.Enabled = False
                    .RotorToolStripMenuItem.Enabled = False
                    .RectifierToolStripMenuItem.Enabled = False
                    .RegulatorToolStripMenuItem.Enabled = False
                    .BrushToolStripMenuItem.Enabled = False
                    .StatorCoilToolStripMenuItem.Enabled = False
                    .StatorCoreToolStripMenuItem.Enabled = False
                    .SlotDefinitionToolStripMenuItem.Enabled = False
                    .ClawPolesToolStripMenuItem.Enabled = False
                    .BrushCollectionToolStripMenuItem.Enabled = False
                    .FieldCoilToolStripMenuItem.Enabled = False
                    .FieldCoreToolStripMenuItem.Enabled = False
                    .FanToolStripMenuItem.Enabled = False
                    .ThermalCoefficientToolStripMenuItem.Enabled = False

                    .CreateToolStripMenuItem.Enabled = False
                    .DeleteToolStripMenuItem.Enabled = False
                    .ImportDataToolStripMenuItem.Enabled = False
                    .Text = .Text & " Expired in : " & mainForm.currentUser.getExpiredDays() - (Today - mainForm.currentUser.getCreatedDate()).TotalDays & " day(s)"
                End With
            Else
                mainForm.Text = mainForm.Text & " Expired in : illimited"
            End If

            System.Windows.Forms.Application.Run(mainForm)
        End If
    End Sub
End Module

Public Class mainForm
    Dim currentAlter As Alternator
    Dim currentStator As StatorAssembly
    Dim currentRotor As Rotor
    Dim currentRectifier As Rectifier
    Dim currentRegulator As Regulator
    Dim currentBrush As Brush
    Dim currentStatorCore As StatorCore
    Dim currentStatorCoil As StatorCoil
    Dim currentSlotDefinition As SlotDefinition
    Dim currentThermalCoefficient As ThermalCoefficient
    Dim currentClawPoles As ClawPoles
    Dim currentBrushCollector As BrushCollector
    Dim currentFieldCore As FieldCore
    Dim currentFieldCoil As FieldCoil
    Dim currentFan As Fan
    Dim currentMagnet As Magnet
    Dim currentMaterialMagnetic As MaterialMagnetic
    Dim currentMaterialConductor As MaterialConductor
    Dim WithEvents searchingResultPage As TabPage
    Dim rightIndexForLeftTabPage(0 To 100) As Integer
    Dim leftIndexForRightTabPage(0 To 100) As Integer
    Dim totalLeftPage As Integer = 0
    Dim totalRightPage As Integer = 0
    Public currentUser As User
    Dim WithEvents modifyUserForm As System.Windows.Forms.Form
    Dim WithEvents adapMenuForm As System.Windows.Forms.Form
    Dim adapterFormClass As adapterForm
    Dim deleteComponentFormClass As DeleteComponentForm
    Dim WithEvents deleteComponentForm As System.Windows.Forms.Form
    Dim noDisplayList() As String = {"version", "editor", "is original", "modified date", "teeth width", "slot width", "wire diameter", "wire width", "wire height"}

    ''' Constants '''
    Const alterRefCol = 4
    Const alterRefRow = 11


    Public Sub addTwoTabs(ByVal leftTab As TabPage, ByVal rightTab As TabPage)
        leftTabControl.Controls.Add(leftTab)
        rightTabControl.Controls.Add(rightTab)
        rightIndexForLeftTabPage(totalLeftPage) = totalRightPage
        leftIndexForRightTabPage(totalRightPage) = totalLeftPage
        totalLeftPage += 1
        totalRightPage += 1
        leftTabControl.SelectedTab = leftTab
    End Sub

    Public Sub setInitInfo(ByRef obj As Object, ByVal version As Integer, ByVal editor As String, ByVal _date As Date, ByVal isOriginal As Integer)
        obj.setVersion(version)
        obj.setEditor(editor)
        obj.setModifiedDate(_date)
        obj.setIsOriginal(isOriginal)
    End Sub

    Private Sub AlternatorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AlternatorToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Alter") Then
            currentAlter = New Alternator()
            ' initializer les infos par défault
            setInitInfo(currentAlter, 0, currentUser.getLogin(), Today, 1)
            'currentAlter = currentAlter.getObjectByKey("TG11", "Alternator", "alternator")
            Dim newItemTabPage As New ObjectPresent(currentAlter, "new Alter")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub StatorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StatorToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Stator") Then
            currentStator = New StatorAssembly()
            setInitInfo(currentStator, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentStator, "new Stator")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub RotorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RotorToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Rotor") Then
            currentRotor = New Rotor()
            setInitInfo(currentRotor, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentRotor, "new Rotor")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub RectifierToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RectifierToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Rectifier") Then
            currentRectifier = New Rectifier()
            setInitInfo(currentRectifier, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentRectifier, "new Rectifier")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub RegulatorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RegulatorToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Regulator") Then
            currentRegulator = New Regulator()
            setInitInfo(currentRegulator, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentRegulator, "new Regulator")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub BrushToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BrushToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Brush") Then
            currentBrush = New Brush()
            setInitInfo(currentBrush, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentBrush, "new Brush")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub StatorCoilToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StatorCoilToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Stator Coil") Then
            currentStatorCoil = New StatorCoil()
            setInitInfo(currentStatorCoil, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentStatorCoil, "new Stator Coil")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub StatorCoreToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StatorCoreToolStripMenuItem.Click

    End Sub

    Private Sub SlotDefinitionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SlotDefinitionToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Slot Definition") Then
            currentSlotDefinition = New SlotDefinition()
            setInitInfo(currentSlotDefinition, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentSlotDefinition, "new Slot Definition")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub ClawPolesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClawPolesToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Claw Poles") Then
            currentClawPoles = New ClawPoles()
            setInitInfo(currentClawPoles, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentClawPoles, "new Claw Poles")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub BrushCollectionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BrushCollectionToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Brush Collector") Then
            currentBrushCollector = New BrushCollector()
            setInitInfo(currentBrushCollector, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentBrushCollector, "new Brush Collection")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub FieldCoreToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FieldCoreToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Field Core") Then
            currentFieldCore = New FieldCore()
            setInitInfo(currentFieldCore, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentFieldCore, "new Field Core")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub FieldCoilToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FieldCoilToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Field Coil") Then
            currentFieldCoil = New FieldCoil()
            setInitInfo(currentFieldCoil, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentFieldCoil, "new Field Coil")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub FanToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FanToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Fan") Then
            currentFan = New Fan()
            setInitInfo(currentFan, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentFan, "new Fan")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub ThermalCoefficientToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ThermalCoefficientToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Thermal Coefficient") Then
            currentThermalCoefficient = New ThermalCoefficient()
            setInitInfo(currentThermalCoefficient, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentThermalCoefficient, "new Thermal Coefficient")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub leftTabControl_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles leftTabControl.SelectedIndexChanged
        If leftTabControl.SelectedIndex >= 0 Then
            rightTabControl.SelectedIndex = rightIndexForLeftTabPage(leftTabControl.SelectedIndex)
        End If
    End Sub

    Private Sub rightTabControl_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rightTabControl.SelectedIndexChanged
        If rightTabControl.SelectedIndex >= 0 Then
            leftTabControl.SelectedIndex = leftIndexForRightTabPage(rightTabControl.SelectedIndex)
        End If
    End Sub

    'Private Sub searchingButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    ' launch the reseach if only we have a key word and a vakue
    '    If searchingKeyBox.Text <> "" And searchingValueBox.Text <> "" Then
    '        ' creation a new right tab page for the searching results
    '        searchingResultPage = New TabPage("Results for '" & searchingKeyBox.Text & " = " & searchingValueBox.Text & " '")
    '        leftIndexForRightTabPage(totalRightPage) = -1
    '        totalRightPage += 1
    '        rightTabControl.Controls.Add(searchingResultPage)
    '        rightTabControl.SelectedTab = searchingResultPage



    '        ' Re-initilize searching zone after 1 search
    '        searchingKeyBox.Text = ""
    '        searchingValueBox.Text = ""
    '    Else
    '        MsgBox("Enter a keyword and a value for a research", vbCritical)
    '    End If
    '   End Sub

    Private Sub searchButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles searchButton.Click
        Dim search As New Searching
        addTwoTabs(search.getLeftTabPage(), search.getRightTabPage)
        search.loadTree()
    End Sub

    ''' <summary>
    ''' Build a complet treenode from a dataBase table with obj which presents it
    ''' </summary>
    ''' <param name="obj"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function buidTreeNodeFromTable(ByVal obj As Object) As TreeNode
        Dim connectionString As String
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim sql As String
        Dim reader As SqlDataReader
        Dim rootNode = New TreeNode()
        Dim source As String = System.Net.Dns.GetHostEntry("cre2-w01526").AddressList(0).ToString
        connectionString = "Data Source=" & source & ";Initial Catalog=AlternatorDatabase; Integrated Security=SSPI;"
        sql = "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG = 'AlternatorDatabase' and TABLE_NAME = '" & obj.tableName & "'"
        connection = New SqlConnection(connectionString)
        Try
            connection.Open()
            command = New SqlCommand(sql, connection)
            reader = command.ExecuteReader()
            Try
                rootNode.Name = getLabelFormName(obj.tableName)
                rootNode.Text = getLabelFormName(obj.tableName)
                rootNode.Tag = obj
                Dim childrenList() As String = Activator.CreateInstance(Type.GetType("WindowsApplication1.IHMClass." & columnNameToFunctionName(obj.tableName), True, True)).childrenList
                While reader.Read()
                    Dim treeNode = New TreeNode()
                    If isMember(childrenList, reader(0)) Then
                        Dim ref As String = obj.getAttribute(columnNameToFunctionName(reader(0)))
                        treeNode = buidTreeNodeFromTable(obj.getObjectByKey(ref, columnNameToFunctionName(reader(0)), reader(0)))
                        treeNode.Name = getLabelFormName(reader(0))
                        treeNode.Text = getLabelFormName(reader(0))
                    Else
                        treeNode.Name = getLabelFormName(reader(0))
                        treeNode.Text = getLabelFormName(reader(0)) & " : " & obj.getAttribute(columnNameToFunctionName(reader(0)))
                    End If
                    If Not isMember(noDisplayList, treeNode.Name) Then
                        rootNode.Nodes.Add(treeNode)
                    End If
                End While
                command.Dispose()
                connection.Close()
            Finally
                reader.Close()
            End Try
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

        ' noeuds supplémentaires
        ' for rotor table
        If obj.tableName = "rotor" Then
            Dim node As TreeNode = buildMagnetList(obj)
            rootNode.Nodes.Add(node)
        End If
        ' for slot definition table
        If obj.tableName = "slot_definition" Then
            Dim index As Integer = rootNode.Nodes.IndexOfKey("slot with parallel sides")
            If obj.getSlotWithParallelSides = 1 Then
                Dim slotWidthNode As New TreeNode
                slotWidthNode.Text = "slot width : " & obj.getAttribute("SlotWidth")
                slotWidthNode.Name = "slot width"
                rootNode.Nodes(index).Nodes.Add(slotWidthNode)
            ElseIf obj.getSlotWithParallelSides = 2 Then
                Dim teethWidthNode As New TreeNode
                teethWidthNode.Text = "teeth width : " & obj.getAttribute("TeethWidth")
                teethWidthNode.Name = "teeth width"
                rootNode.Nodes(index).Nodes.Add(teethWidthNode)
            End If
        End If
        ' for stator coil table
        If obj.tableName = "stator_coil" Then
            Dim index As Integer = rootNode.Nodes.IndexOfKey("wire type")
            If obj.getWireType = 1 Then ' round type
                Dim wireDiameter As New TreeNode
                wireDiameter.Text = "wire diameter : " & obj.getAttribute("WireDiameter")
                wireDiameter.Name = "wire diameter"
                rootNode.Nodes(index).Nodes.Add(wireDiameter)
            ElseIf obj.getWireType = 2 Then ' U pin
                Dim wireWidth As New TreeNode
                wireWidth.Text = "wire width : " & obj.getAttribute("WireWidth")
                wireWidth.Name = "wire width"
                rootNode.Nodes(index).Nodes.Add(wireWidth)

                Dim wireHeight As New TreeNode
                wireHeight.Text = "wire height : " & obj.getAttribute("WireHeight")
                wireHeight.Name = "wire height"
                rootNode.Nodes(index).Nodes.Add(wireHeight)
            End If
        End If

        Return rootNode
    End Function

    ''' <summary>
    ''' transform the dataBase column name to label for TreeNode.Text
    ''' </summary>
    ''' <param name="name"></param>
    ''' <returns>label for TreeNode.Text</returns>
    ''' <remarks></remarks>
    Public Function getLabelFormName(ByVal name) As String
        Dim label As String = ""
        For Each e As Char In name
            If e = "_" Then
                label = label & " "
            Else
                label = label & e
            End If
        Next
        Return label
    End Function

    ''' <summary>
    ''' Transform the label of TreeView.Text to dataBase column Name
    ''' </summary>
    ''' <param name="name"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function toDataBaseColumnName(ByVal name) As String
        Dim label As String = ""
        For Each e As Char In name
            If e = " " Then
                label = label & "_"
            Else
                label = label & e
            End If
        Next
        Return label
    End Function

    Public Function columnNameToFunctionName(ByVal name As String) As String
        Dim _name As String = ""
        Dim mark As Boolean = True
        For Each c As Char In name
            If c = "_" Or c = " " Then
                mark = True
            ElseIf mark = True Then
                _name = _name & c.ToString.ToUpper
                mark = False
            Else
                _name = _name & c
            End If
        Next
        Return _name
    End Function

    ''' <summary>
    ''' Check if a String is member of a list of string
    ''' </summary>
    ''' <param name="list"></param>
    ''' <param name="member"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function isMember(ByVal list() As String, ByVal member As String) As Boolean
        Dim ok As Boolean = False
        For i As Integer = 0 To list.Length - 1 Step 1
            If list(i) = member Then
                ok = True
                Exit For
            End If
        Next
        Return ok
    End Function

    Private Sub CreateToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CreateToolStripMenuItem.Click
        Dim createUserClass As New CreateUserForm
        Dim createUserForm As Form = createUserClass.getForm()
        createUserForm.Show()
    End Sub

    Private Sub DeleteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteToolStripMenuItem.Click
        Dim deleteUserClass As New DeleteUserForm
        Dim deleteUserForm As Form = deleteUserClass.getForm()
        deleteUserForm.Show()
    End Sub

    Private Sub ModifyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ModifyToolStripMenuItem.Click
        Dim modifyUserClass As CreateUserForm
        modifyUserClass = New CreateUserForm(False)
        modifyUserClass.loadFormFromUserProfile(currentUser)
        modifyUserForm = modifyUserClass.getForm()
        modifyUserForm.Show()
    End Sub

    Private Sub modifyUserForm_FormDispose(ByVal sender As System.Object, ByVal e As EventArgs) Handles modifyUserForm.Disposed
        ' mise à jour
        currentUser = New User(currentUser.getLogin())
    End Sub

    Public Function loadItemsToComboBox(ByVal tableName As String, ByVal targetCol As String, ByVal condition As String, ByVal displayMember As String, ByVal valueMember As String) As ComboBox
        Dim cbBox As New ComboBox
        Dim connectionString As String
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim sql As String
        Dim source As String = System.Net.Dns.GetHostEntry("cre2-w01526").AddressList(0).ToString
        connectionString = "Data Source=" & source & ";Initial Catalog=AlternatorDatabase; Integrated Security=SSPI;"
        sql = "SELECT " & targetCol & " FROM " & tableName & " " & condition
        connection = New SqlConnection(connectionString)
        Try
            connection.Open()
            command = New SqlCommand(sql, connection)
            Dim dscmd As New SqlDataAdapter(sql, connection)
            Dim ds As New DataSet
            dscmd.Fill(ds)
            cbBox.DataSource = ds.Tables(0)
            cbBox.DisplayMember = displayMember
            cbBox.ValueMember = valueMember
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        Return cbBox
    End Function

    Private Sub AdaptationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AdaptationToolStripMenuItem.Click
        adapterFormClass = New adapterForm(currentUser)
        adapMenuForm = adapterFormClass.getForm()
        adapMenuForm.Show()
    End Sub

    Private Sub adapMenuForm_FormDispose(ByVal sender As System.Object, ByVal e As EventArgs) Handles adapMenuForm.Disposed
        If adapterFormClass.getComponentRef() Is Nothing Or adapterFormClass.getComponentName() Is Nothing Then
            Exit Sub
        End If
        Dim obj As New Component
        obj = obj.getObjectByKey(adapterFormClass.getComponentRef(), columnNameToFunctionName(adapterFormClass.getComponentName()), adapterFormClass.getComponentName())
        If adapterFormClass.isOverWrite() Then
            Dim newItemTabPage As New ObjectPresent(obj, "Modifier")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            Try
                obj.setVersion(obj.getVersion() + 1)
                obj.update("version")
                obj.setRef(obj.getRef() & "_ADAP_" & obj.getVersion().ToString)
                obj.insert()
                setInitInfo(obj, 0, currentUser.getLogin(), Today, 0) ' version adaptée
                obj.updateAll()
                Dim newItemTabPage As New ObjectPresent(obj, "Adapter", True)
                newItemTabPage.loadTree()
                addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub DeleteComponentToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteComponentToolStripMenuItem.Click
        deleteComponentFormClass = New DeleteComponentForm
        deleteComponentForm = deleteComponentFormClass.getForm
        deleteComponentForm.Show()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Dispose()
    End Sub

    Private Sub ImportDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImportDataToolStripMenuItem.Click
        Dim openFile As New ImportDataForm
        Dim fileName As String = openFile.getFileName()
        If fileName <> "" Then
            Dim excelApp As Excel.Application
            Dim excelWorkSheet As Worksheet

            Dim excelBook As Workbook
            excelApp = New Excel.Application
            excelBook = excelApp.Workbooks.Open(fileName)
            excelWorkSheet = excelBook.Worksheets("sheet1")

            Dim alter As New Alternator()
            setInitInfo(alter, 0, currentUser.getLogin(), Today, 1)
            alter.setRef(excelWorkSheet.Cells(alterRefRow, alterRefCol).value)
            If alter.exist("alternator", alter.getRef()) Then
                MsgBox("Alternator was already in the DataBase", vbCritical)
            Else
                importAlternator(alter, excelWorkSheet)
            End If

            excelBook.Close(False)
            excelApp.Quit()
            Me.Activate()
        End If
    End Sub

    Private Sub ExportDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportDataToolStripMenuItem.Click
        Dim exportData As New ExportDataForm
        Dim form As Form = exportData.getForm()
        form.Show()
    End Sub

    Private Sub importAlternator(ByRef alter As Alternator, ByVal excelWorkSheet As Worksheet)
        ' importe ses paramètres généraux    
        Dim row As Integer = 11
        Dim col As Integer = 4
        readDataToObject(row, col, 4, excelWorkSheet, alter)

        row += 1 ' 1 ligne blance
        ' importe sa stator
        Dim stator As New StatorAssembly
        row += 1 ' 1 ligne de nom
        setInitInfo(stator, 0, currentUser.getLogin(), Today, 1)
        row += 1
        stator.setRef(excelWorkSheet.Cells(row, col).value)
        readDataToObject(row, col, 14, excelWorkSheet, stator)
        alter.setStatorAssembly(stator.getRef())

        ' winding stator
        row += 1 ' 1 ligne blance
        Dim windingStator As New WindingStator
        row += 1 ' 1 ligne de nom
        setInitInfo(windingStator, 0, currentUser.getLogin(), Today, 1)
        row += 1
        windingStator.setRef(excelWorkSheet.Cells(row, col).value)
        readDataToObject(row, col, 1, excelWorkSheet, windingStator)
        stator.setWindingStator(windingStator.getRef())

        ' Stator Stack
        row += 1 ' 1 ligne blacne
        Dim statorStack As New StatorStack
        row += 1 ' 1 ligne de nom
        setInitInfo(statorStack, 0, currentUser.getLogin(), Today, 1)
        row += 1
        statorStack.setRef(excelWorkSheet.Cells(row, col).value)
        readDataToObject(row, col, 16, excelWorkSheet, statorStack)
        windingStator.setStatorStack(statorStack.getRef())

        ' Rotor Assembly
        row += 1 ' 1 ligne blance
        Dim rotor As New Rotor
        row += 1 ' 1 ligne de nom
        setInitInfo(rotor, 0, currentUser.getLogin(), Today, 1)
        row += 1
        rotor.setRef(excelWorkSheet.Cells(row, col).value)
        readDataToObject(row, col, 11, excelWorkSheet, rotor)
        alter.setRotor(rotor.getRef())

        ' Claw Poles
        row += 1 ' 1 ligne blance
        Dim clawPoles As New ClawPoles
        row += 1 ' 1 ligne de nom
        setInitInfo(clawPoles, 0, currentUser.getLogin(), Today, 1)
        row += 1
        clawPoles.setRef(excelWorkSheet.Cells(row, col).value)
        readDataToObject(row, col, 22, excelWorkSheet, clawPoles)

        ' Field Coil
        row += 1 ' 1 ligne blance
        Dim fieldCoil As New FieldCoil
        row += 1 ' 1 ligne de nom
        setInitInfo(fieldCoil, 0, currentUser.getLogin(), Today, 1)
        row += 1
        fieldCoil.setRef(excelWorkSheet.Cells(row, col).value)
        readDataToObject(row, col, 5, excelWorkSheet, fieldCoil)
        

        ' sauvegarder
        updateOrInsert(fieldCoil)
        updateOrInsert(clawPoles)
        updateOrInsert(rotor)
        updateOrInsert(statorStack)
        updateOrInsert(windingStator)
        updateOrInsert(stator)
        updateOrInsert(alter)
        MsgBox("Data Imported !!!")
    End Sub

    Private Sub updateOrInsert(ByVal obj As Object)
        With obj
            If Not .exist(.tableName, .getRef()) Then
                .insert()
            End If
            .updateAll()
        End With
    End Sub

    Private Sub readDataToObject(ByRef row As Integer, ByVal col As Integer, ByVal nberLines As Integer, ByVal excelWorkSheet As Worksheet, ByRef obj As Component)
        For i As Integer = 1 To nberLines Step 1
            row += 1
            Dim name As String = excelWorkSheet.Cells(row, col - 1).value
            Dim value As Object
            If IsNumeric(excelWorkSheet.Cells(row, col).value) Or obj.isDouble(excelWorkSheet.Cells(row, col).value) Then
                If name <> "Resistivity" Then
                    value = Math.Round(Double.Parse(excelWorkSheet.Cells(row, col).value), 3)
                Else
                    value = Double.Parse(excelWorkSheet.Cells(row, col).value)
                End If
            Else
                value = excelWorkSheet.Cells(row, col).value
            End If
            obj.setAttribute(columnNameToFunctionName(name), value)
        Next
    End Sub

    Private Function buildMagnetList(ByVal rotor As Rotor) As TreeNode
        Dim node As New TreeNode
        node.Text = "magnets"
        node.Name = "magnets"
        Dim magnetList() As String = rotor.getMagnetList()
        Dim index As Integer = 0
        While magnetList(index) <> ""
            Dim childNode As New TreeNode
            Dim rotorMagnet As RotorMagnet = rotor.getRotorMagnet(magnetList(index))
            childNode.Text = "Magnet Ref : " & magnetList(index) & " quantity : " & rotorMagnet.getQuantity
            childNode.Name = magnetList(index)
            node.Nodes.Add(childNode)
            index += 1
            childNode.Tag = rotorMagnet
        End While
        Return node
    End Function

    Private Sub MagnetToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MagnetToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Magnet") Then
            currentMagnet = New Magnet()
            setInitInfo(currentMagnet, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentMagnet, "new Magnet")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Public Function tableNameToFunctionName(ByVal name As String) As String
        Dim _name As String = ""
        For Each e As Char In name
            If e = " " Then
                e = "_"
            End If
            _name += e
        Next
        Return _name
    End Function

    Private Sub MaterialConductorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MaterialConductorToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Material Conductor") Then
            currentMaterialConductor = New MaterialConductor()
            setInitInfo(currentMaterialConductor, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentMaterialConductor, "new Material Conductor")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub MaterialMagneticToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MaterialMagneticToolStripMenuItem.Click
        If Not leftTabControl.Controls.ContainsKey("new Material Magnetic") Then
            currentMaterialMagnetic = New MaterialMagnetic()
            setInitInfo(currentMaterialMagnetic, 0, currentUser.getLogin(), Today, 1)
            Dim newItemTabPage As New ObjectPresent(currentMaterialMagnetic, "new Material Magnetic")
            newItemTabPage.loadTree()
            addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        Else
            MsgBox("Can create this new item", vbCritical)
        End If
    End Sub

    Private Sub onFormSizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.SizeChanged
        leftTabControl.Size = SplitContainer1.Panel1.Size
        rightTabControl.Size = SplitContainer1.Panel2.Size
        For i As Integer = 0 To leftTabControl.TabPages.Count() - 1 Step 1
            leftTabControl.TabPages(i).Size = leftTabControl.Size
        Next
        For i As Integer = 0 To rightTabControl.TabPages.Count() - 1 Step 1
            rightTabControl.TabPages(i).Size = rightTabControl.Size
        Next
    End Sub

    Private Sub DisconnectToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisconnectToolStripMenuItem.Click
        Me.Text = "Alter v.0.1"
        ' Supprimer tous les objets présentés
        leftTabControl.Controls.Clear()
        rightTabControl.Controls.Clear()
        Dim loginFormClass As New LoginForm()
        If loginFormClass.getConnected() Then
            Me.currentUser = loginFormClass.getUser()
            Me.Text = Me.Text & " Login as " & Me.currentUser.getLogin()
            ' déactiver les fonctions selon la droit d'utilisateur
            Dim user As User = loginFormClass.getUser()
            Dim value As Boolean = True
            If user.getUserRight() = 2 Then ' standard user
                value = False
                Me.Text = Me.Text & " Expired in : " & Me.currentUser.getExpiredDays() - (Today - Me.currentUser.getCreatedDate()).TotalDays & " day(s)"
            Else
                Me.Text = Me.Text & " Expired in : illimited"
            End If

            With Me
                .NewToolStripMenuItem.Enabled = value
                .AlternatorToolStripMenuItem.Enabled = value
                .StatorToolStripMenuItem.Enabled = value
                .RotorToolStripMenuItem.Enabled = value
                .RectifierToolStripMenuItem.Enabled = value
                .RegulatorToolStripMenuItem.Enabled = value
                .BrushToolStripMenuItem.Enabled = value
                .StatorCoilToolStripMenuItem.Enabled = value
                .StatorCoreToolStripMenuItem.Enabled = value
                .SlotDefinitionToolStripMenuItem.Enabled = value
                .ClawPolesToolStripMenuItem.Enabled = value
                .BrushCollectionToolStripMenuItem.Enabled = value
                .FieldCoilToolStripMenuItem.Enabled = value
                .FieldCoreToolStripMenuItem.Enabled = value
                .FanToolStripMenuItem.Enabled = value
                .ThermalCoefficientToolStripMenuItem.Enabled = value

                .CreateToolStripMenuItem.Enabled = value
                .DeleteToolStripMenuItem.Enabled = value
                .ImportDataToolStripMenuItem.Enabled = value
            End With
        Else
            Me.Dispose()
        End If
    End Sub

    Private Sub CalculFlowToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculFlowToolStripMenuItem.Click
        Dim calcul As New CalculForm
        addTwoTabs(calcul.getLeftTabPage, calcul.getRightTabPage)
    End Sub

End Class

Public Class ObjectPresent
    Inherits mainForm
    Private obj As Object
    Private WithEvents leftTabPage As TabPage
    Private WithEvents rightTabPage As TabPage
    Private WithEvents treeView As TreeView
    Private WithEvents itemsTreeView As TreeView
    Private modifyZone As System.Windows.Forms.GroupBox
    Private chooseItemZone As System.Windows.Forms.GroupBox
    Private WithEvents valueLabel As System.Windows.Forms.Label
    Private WithEvents valueTextBox As System.Windows.Forms.TextBox
    Private WithEvents modifyButton As System.Windows.Forms.Button
    Private WithEvents findButton As System.Windows.Forms.Button
    Private WithEvents saveButton As System.Windows.Forms.Button
    Private WithEvents closeButton As System.Windows.Forms.Button
    Private leftTabPageIndex As Integer
    Private rightTabPageIndex As Integer
    Private inAdapterMode As Boolean = False
    Private magnetModifyZone As System.Windows.Forms.GroupBox
    Private WithEvents magnetRefText As System.Windows.Forms.TextBox
    Private WithEvents magnetAddButton As System.Windows.Forms.Button
    Private WithEvents magnetSubButton As System.Windows.Forms.Button
    Private WithEvents listMagnetButton As System.Windows.Forms.Button
    Private WithEvents deleteMagnetButton As System.Windows.Forms.Button
    Private descriptionZone As System.Windows.Forms.GroupBox
    Private descriptionText As System.Windows.Forms.TextBox
    Private illustrationZone As System.Windows.Forms.GroupBox
    Private illustrationPicture As System.Windows.Forms.PictureBox
    Private illustrationSlot As New System.Windows.Forms.Panel
    Private myGraphic As System.Drawing.Graphics

    ''' <summary>
    ''' Constructor, initialize all the controls of right and left pages
    ''' </summary>
    ''' <param name="_obj"></param>
    ''' <param name="tabText"></param>
    ''' <remarks></remarks>
    Sub New(ByVal _obj As Object, ByVal tabText As String, Optional ByVal _inAdapterMode As Boolean = vbFalse)
        obj = _obj
        leftTabPage = New TabPage(tabText)
        leftTabPage.Name = tabText
        leftTabPage.Size = SplitContainer1.Panel1.Size
        rightTabPage = New TabPage("Description")
        rightTabPage.Size = SplitContainer1.Panel2.Size

        ' main tree view
        treeView = New TreeView()
        treeView.Location = New System.Drawing.Point(leftTabPage.Left, leftTabPage.Top)
        treeView.Width = leftTabPage.Width - 20
        treeView.Height = (leftTabPage.Height / 5) * 3
        treeView.HideSelection = False

        ' modify zone to edit treeview's value
        modifyZone = New System.Windows.Forms.GroupBox()
        modifyZone.Text = "Modify"
        modifyZone.Location = New System.Drawing.Point(treeView.Left, treeView.Bottom)
        modifyZone.Width = leftTabPage.Width - 20
        modifyZone.Height = (leftTabPage.Height / 10) * 1.25
        valueLabel = New System.Windows.Forms.Label()
        valueLabel.Text = "Value : "
        valueLabel.Width = 50
        valueLabel.Location = New System.Drawing.Point(15, 20)
        valueTextBox = New System.Windows.Forms.TextBox()
        valueTextBox.Location = New System.Drawing.Point(15 + valueLabel.Width, 20)
        valueTextBox.Width = 150
        findButton = New System.Windows.Forms.Button()
        findButton.Text = "Find"

        findButton.Width = 100
        findButton.Enabled = False
        modifyButton = New System.Windows.Forms.Button()
        modifyButton.Text = "Save"
        modifyButton.Location = New System.Drawing.Point(modifyZone.Width - 20 - modifyButton.Width, modifyZone.Height - 10 - modifyButton.Height)
        findButton.Location = New System.Drawing.Point(modifyButton.Left - findButton.Width - 10, modifyButton.Top)
        modifyButton.Width = 100
        modifyZone.Controls.Add(valueLabel)
        modifyZone.Controls.Add(valueTextBox)
        modifyZone.Controls.Add(modifyButton)
        modifyZone.Controls.Add(findButton)
        modifyZone.Enabled = False

        ' choose item zone
        chooseItemZone = New System.Windows.Forms.GroupBox()
        chooseItemZone.Text = "Items to choose : "
        chooseItemZone.Location = New System.Drawing.Point(modifyZone.Left, modifyZone.Bottom)
        chooseItemZone.Width = leftTabPage.Width - 20
        chooseItemZone.Height = (leftTabPage.Height / 5) * 1
        itemsTreeView = New TreeView()
        itemsTreeView.AutoSize = True
        itemsTreeView.Dock = DockStyle.Fill
        itemsTreeView.HideSelection = False
        chooseItemZone.Controls.Add(itemsTreeView)
        chooseItemZone.Enabled = False

        ' magnet edition zone
        magnetModifyZone = New System.Windows.Forms.GroupBox()
        magnetModifyZone.Text = "Magnet Edit"
        magnetModifyZone.Location = modifyZone.Location
        magnetModifyZone.Size = modifyZone.Size
        magnetRefText = New System.Windows.Forms.TextBox
        magnetRefText.Width += 50
        magnetRefText.BackColor = Color.White
        magnetRefText.Location = New System.Drawing.Point(20, 20)
        magnetRefText.Enabled = False
        magnetModifyZone.Controls.Add(magnetRefText)
        magnetAddButton = New System.Windows.Forms.Button()
        magnetAddButton.Text = "+"
        magnetAddButton.TextAlign = ContentAlignment.MiddleCenter
        magnetAddButton.Height = magnetRefText.Height
        magnetAddButton.Width = magnetAddButton.Height
        magnetAddButton.Location = New System.Drawing.Point(magnetModifyZone.Right - 3 * magnetAddButton.Width - 16, 20)
        magnetModifyZone.Controls.Add(magnetAddButton)
        magnetSubButton = New System.Windows.Forms.Button()
        magnetSubButton.Text = "-"
        magnetSubButton.TextAlign = ContentAlignment.MiddleCenter
        magnetSubButton.Size = magnetAddButton.Size
        magnetSubButton.Location = New System.Drawing.Point(magnetModifyZone.Right - 2 * magnetSubButton.Width - 13, 20)
        magnetModifyZone.Controls.Add(magnetSubButton)
        deleteMagnetButton = New System.Windows.Forms.Button()
        deleteMagnetButton.Text = "X"
        deleteMagnetButton.TextAlign = ContentAlignment.MiddleCenter
        deleteMagnetButton.Size = magnetAddButton.Size
        deleteMagnetButton.Location = New System.Drawing.Point(magnetModifyZone.Right - deleteMagnetButton.Width - 10, 20)
        magnetModifyZone.Controls.Add(deleteMagnetButton)
        listMagnetButton = New System.Windows.Forms.Button()
        listMagnetButton.Text = "List..."
        listMagnetButton.TextAlign = ContentAlignment.MiddleCenter
        listMagnetButton.Location = New System.Drawing.Point(magnetModifyZone.Right - 10 - listMagnetButton.Width, magnetModifyZone.Height - 10 - listMagnetButton.Height)
        magnetModifyZone.Controls.Add(listMagnetButton)

        descriptionZone = New System.Windows.Forms.GroupBox
        descriptionZone.Location = New System.Drawing.Point(0, 0)
        descriptionZone.Width = rightTabPage.Width - 15
        descriptionZone.Height = (rightTabPage.Height / 10) * 1.25
        descriptionZone.Text = "Infos : "
        descriptionText = New System.Windows.Forms.TextBox
        descriptionText.Location = New System.Drawing.Point(5, 15)
        descriptionText.Width = descriptionZone.Width - 10
        descriptionText.Height = descriptionZone.Height - 25
        descriptionText.Multiline = True
        descriptionText.Enabled = False
        descriptionZone.Controls.Add(descriptionText)
        descriptionText.BackColor = Color.White
        illustrationZone = New System.Windows.Forms.GroupBox
        illustrationZone.Text = "Illustration : "
        illustrationZone.Location = New System.Drawing.Point(descriptionZone.Left, descriptionZone.Bottom)
        illustrationZone.Width = descriptionZone.Width
        illustrationZone.Height = (rightTabPage.Height / 10) * 7.55
        illustrationPicture = New System.Windows.Forms.PictureBox
        illustrationPicture.AutoSize = True
        illustrationPicture.Dock = DockStyle.Fill
        illustrationSlot.AutoSize = True
        illustrationSlot.Dock = DockStyle.Fill
        illustrationZone.Controls.Add(illustrationPicture)
        illustrationZone.Controls.Add(illustrationSlot)

        closeButton = New System.Windows.Forms.Button()
        closeButton.Text = "Close"
        closeButton.Location = New System.Drawing.Point(chooseItemZone.Right - closeButton.Width, chooseItemZone.Bottom)
        leftTabPage.Controls.Add(modifyZone)
        leftTabPage.Controls.Add(treeView)
        leftTabPage.Controls.Add(chooseItemZone)
        leftTabPage.Controls.Add(closeButton)
        leftTabPage.Controls.Add(magnetModifyZone)
        magnetModifyZone.Visible = False
        inAdapterMode = _inAdapterMode

        rightTabPage.Controls.Add(descriptionZone)
        rightTabPage.Controls.Add(illustrationZone)

        'modifyButton.AutoToolTip = True
        'modifyButton.ToolTipText = "Save a value to parameter"
    End Sub

    Function getleftTabPage() As TabPage
        Return leftTabPage
    End Function

    ''' <summary>
    ''' buil the main tree view
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub loadTree()
        treeView.Nodes.Clear()
        Dim root As New TreeNode
        root = buidTreeNodeFromTable(obj)
        treeView.Nodes.Add(root)
    End Sub

    Private Sub treeView_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles treeView.AfterSelect
        modifyZone.Enabled = True
        Dim obj As Object = e.Node.Tag
        If Not e.Node.Parent Is Nothing Then
            If e.Node.Name = "magnets" Or e.Node.Parent.Name = "magnets" Then
                modifyZone.Visible = False
                magnetModifyZone.Visible = True
                If e.Node.Parent.Name = "magnets" Then 'on clique sur la référence d'une aiment
                    magnetRefText.Text = obj.getMagnetRef()
                    magnetAddButton.Enabled = True
                    deleteMagnetButton.Enabled = True
                    If obj.getQuantity() > 1 Then
                        magnetSubButton.Enabled = True
                    Else
                        magnetSubButton.Enabled = False
                    End If
                Else
                    magnetRefText.Text = ""
                    magnetAddButton.Enabled = False
                    magnetSubButton.Enabled = False
                    deleteMagnetButton.Enabled = False
                End If
                Exit Sub
            End If
        End If

        valueTextBox.Text = ""
        modifyZone.Visible = True

        magnetModifyZone.Visible = False
        itemsTreeView.Nodes.Clear()
        listMagnetButton.Text = "List..."

        If obj Is Nothing Then
            Dim parent As TreeNode = e.Node.Parent
            While obj Is Nothing
                obj = parent.Tag
                parent = parent.Parent
            End While
            valueTextBox.Text = obj.getAttribute(columnNameToFunctionName(e.Node.Name))
            getFieldInfos(obj, e.Node)

            If e.Node.Name = "ref" And Not e.Node.Parent.Parent Is Nothing Then
                findButton.Enabled = True
            Else
                findButton.Enabled = False
                chooseItemZone.Enabled = False
            End If

            If e.Node.Parent.Level = 0 And e.Node.Name = "ref" And obj.getRef() <> "" Then
                modifyButton.Enabled = False
            Else
                modifyButton.Enabled = True
            End If
        Else
            modifyZone.Enabled = False
            If Not e.Node.Parent Is Nothing Then
                getFieldInfos(e.Node.Parent.Tag, e.Node)
            End If
        End If
    End Sub

    Private Sub getFieldInfos(ByVal obj As Object, ByVal e As TreeNode)
        descriptionText.Text = ""
        illustrationPicture.ImageLocation = ""
        illustrationPicture.SizeMode = AutoSizeMode
        If Not obj.getFieldInfo(tableNameToFunctionName(e.Name), "description") Is Nothing Then
            descriptionText.Text = "Descripstion : " & obj.getFieldInfo(tableNameToFunctionName(e.Name), "description").ToString & vbCrLf
        End If
        If Not obj.getFieldInfo(tableNameToFunctionName(e.Name), "data_type") Is Nothing Then
            descriptionText.Text += "Data Type : " & obj.getFieldInfo(tableNameToFunctionName(e.Name), "data_type").ToString & vbCrLf
        End If
        If Not obj.getFieldInfo(tableNameToFunctionName(e.Name), "value_min") Is Nothing Then
            descriptionText.Text += "Minimum Value : " & obj.getFieldInfo(tableNameToFunctionName(e.Name), "value_min").ToString & vbCrLf
        End If
        If Not obj.getFieldInfo(tableNameToFunctionName(e.Name), "value_max") Is Nothing Then
            descriptionText.Text += "Maximum Value : " & obj.getFieldInfo(tableNameToFunctionName(e.Name), "value_max").ToString & vbCrLf
        End If
        If Not obj.getFieldInfo(tableNameToFunctionName(e.Name), "data_set") Is Nothing Then
            descriptionText.Text += "Data set (for enum type) : " & obj.getFieldInfo(tableNameToFunctionName(e.Name), "data_set").ToString & vbCrLf
        End If

        If leftTabPage.Text.Contains("new") = False Then ' on montre les shapes, les chart seulement en cas d'une modification (données completes)
            If obj.tableName = "material_magnetic" And e.Name = "ref" Then ' Illustré par graphe
                If Not e.Parent.Level = 0 Then
                    illustrationPicture.Visible = True
                    If e.Parent.Parent.Tag.tableName = "field_core" Then
                        createChart(2, obj)
                    Else
                        createChart(1, obj)
                    End If
                End If
            ElseIf Not e.Parent.Tag Is Nothing Then
                If e.Parent.Tag.tableName = "stator" And e.Name = "ref" Then
                    If Not e.Parent.Level = 0 Then
                        createShapes(e)
                    End If
                ElseIf obj.getFieldInfo(tableNameToFunctionName(e.Name), "have_picture") = 1 Then
                    illustrationPicture.Visible = True
                    Console.WriteLine("e:\documents and settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\images\" & obj.tableName & "_" & e.Name & ".bmp")
                    illustrationPicture.ImageLocation = "e:\documents and settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\images\" & obj.tableName & "_" & e.Name & ".bmp"
                End If
            End If
        End If
    End Sub

    Private Sub createChart(ByVal type As Integer, ByVal obj As MaterialMagnetic)
        Dim excelApp As Excel.Application
        Dim excelWorkSheet As Worksheet

        Dim excelBook As Workbook
        excelApp = New Excel.Application
        excelBook = excelApp.Workbooks.Open("e:\documents and settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\calcul\DEBIT_tri_TG11.xls", Password:="aquarious")
        If excelBook.HasPassword = False Then
            excelBook.Password = "aquarious"
        End If
        excelWorkSheet = excelBook.Worksheets("Material")

        Select Case type
            Case 1 ' stator
                excelWorkSheet.Cells(37, 7) = obj.getBs()
                excelWorkSheet.Cells(38, 7) = obj.getMu()
                excelWorkSheet.Cells(39, 7) = obj.getHc0()
                excelWorkSheet.Cells(40, 7) = obj.getMu0()
            Case 2
                excelWorkSheet.Cells(37, 8) = obj.getBs()
                excelWorkSheet.Cells(38, 8) = obj.getMu()
                excelWorkSheet.Cells(39, 8) = obj.getHc0()
                excelWorkSheet.Cells(40, 8) = obj.getMu0()
        End Select

        Dim chart As Excel.Chart

        chart = excelWorkSheet.ChartObjects(type).chart

        Try
            Dim re As Boolean = chart.Export("E:\Documents and Settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\images\chart.jpg", "JPEG", False)
        Catch e As Exception
            Console.Write(e.ToString)
        End Try

        illustrationPicture.Visible = True
        illustrationSlot.Visible = False
        illustrationPicture.ImageLocation = "E:\Documents and Settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\images\chart.jpg"
        excelBook.Close(False)
        excelApp.Quit()
    End Sub

    Private Sub modifyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles modifyButton.Click
        Dim selectedNode As TreeNode = treeView.SelectedNode
        If Not selectedNode Is Nothing Then
            Dim parent As TreeNode = selectedNode.Parent
            Dim obj As Object = selectedNode.Tag
            If obj Is Nothing Then ' it is not a node, try to find an associate object
                While obj Is Nothing
                    obj = parent.Tag
                    parent = parent.Parent
                End While
            End If

            If selectedNode.Parent.Level = 0 Then ' if at root we create a new object
                If selectedNode.Name <> "ref" And obj.getRef() = "" Then
                    MsgBox("Enter a reference before saving", vbCritical)
                    Exit Sub
                ElseIf selectedNode.Name = "ref" And obj.getRef() = "" Then
                    If obj.exist(obj.tableName, valueTextBox.Text) Then
                        MsgBox("Reference exists !!", vbCritical)
                        Exit Sub
                    End If
                    Try
                        obj.setRef(valueTextBox.Text)
                        obj.insert()
                        obj.updateAll()
                        selectedNode.Text = selectedNode.Name & " : " & valueTextBox.Text
                        modifyButton.Enabled = False ' we wont see the save button anymore after saving a reference of new object
                        Exit Sub
                    Catch ex As Exception
                        MsgBox(ex.ToString)
                    End Try
                End If
            End If

            If selectedNode.Name = "ref" Then ' if we are modifying a reference, we have to check before editing it
                If Not obj.exist(obj.tableName, valueTextBox.Text) Then
                    MsgBox("Reference does not exist", vbCritical)
                    Exit Sub
                End If

                Dim parentObject As Object = selectedNode.Parent.Parent.Tag
                If parentObject.getRef() = "" Then
                    MsgBox("Enter a reference before saving", vbCritical)
                    Exit Sub
                End If

                Try
                    ' update dataBase
                    parentObject.setAttribute(columnNameToFunctionName(obj.tableName), valueTextBox.Text)
                    If Not inAdapterMode Then
                        parentObject.update(toDataBaseColumnName(obj.tableName))
                    Else
                        saveAdaptation(selectedNode.Parent.Parent)
                    End If

                    ' update tree view
                    Dim selectedNodeParent As TreeNode = selectedNode.Parent
                    obj = obj.getObjectByKey(valueTextBox.Text, columnNameToFunctionName(obj.tableName), obj.tableName)
                    Dim index As Integer = selectedNodeParent.Parent.Nodes.IndexOf(selectedNodeParent)
                    selectedNodeParent.Parent.Nodes.Insert(index, buidTreeNodeFromTable(obj))
                    treeView.Nodes.Remove(selectedNode.Parent)
                Catch ex As Exception
                    MsgBox(ex.ToString)
                End Try
            Else
                If obj.getRef() = "" Then
                    MsgBox("Enter a reference before saving", vbCritical)
                    Exit Sub
                End If
                Try
                    If checkValueField(obj.tableName, selectedNode.Name, valueTextBox.Text) Then 'check the new value for the field
                        ' update DataBase
                        obj.setAttribute(columnNameToFunctionName(selectedNode.Name), valueTextBox.Text)

                        ' noeuds supplémentaires
                        If selectedNode.Name = "slot with parallel sides" Then
                            If valueTextBox.Text = "1" Then
                                If Not selectedNode.Parent.Nodes.ContainsKey("slot width") Then
                                    addChildNode(selectedNode, obj, "slot width")
                                End If
                                removeChildNode(selectedNode, "teeth width")
                            ElseIf valueTextBox.Text = "2" Then
                                If Not selectedNode.Nodes.ContainsKey("teeth width") Then
                                    addChildNode(selectedNode, obj, "teeth width")
                                End If
                                removeChildNode(selectedNode, "slot width")
                            End If
                        End If

                        If selectedNode.Name = "wire type" Then
                            If valueTextBox.Text = "1" Then
                                If Not selectedNode.Parent.Nodes.ContainsKey("wire diameter") Then
                                    addChildNode(selectedNode, obj, "wire diameter")
                                End If
                                removeChildNode(selectedNode, "wire width")
                                removeChildNode(selectedNode, "wire height")
                            ElseIf valueTextBox.Text = "2" Then
                                If Not selectedNode.Nodes.ContainsKey("wire width") Then
                                    addChildNode(selectedNode, obj, "wire width")
                                    addChildNode(selectedNode, obj, "wire height")
                                End If
                                removeChildNode(selectedNode, "wire diameter")
                            End If
                        End If
                        If Not inAdapterMode Then
                            obj.update(toDataBaseColumnName(selectedNode.Name))
                        Else
                            saveAdaptation(selectedNode.Parent)
                        End If
                        ' update TreeView
                        selectedNode.Text = selectedNode.Name & " : " & valueTextBox.Text
                        modifyZone.Enabled = False
                    Else
                        MsgBox("Invalid value", vbCritical)
                    End If
                Catch ex As Exception
                    MsgBox(ex.ToString)
                End Try
            End If
        End If
        chooseItemZone.Enabled = False
    End Sub

    Private Sub addChildNode(ByRef node As TreeNode, ByRef obj As Object, ByVal nodeName As String)
        Dim cNode As New TreeNode
        cNode.Text = nodeName & " : " & obj.getAttribute(columnNameToFunctionName(nodeName))
        cNode.Name = nodeName
        node.Nodes.Add(cNode)
    End Sub

    Private Sub removeChildNode(ByRef node As TreeNode, ByVal nodeName As String)
        Dim index As Integer = -1
        index = node.Nodes.IndexOfKey(nodeName)
        If index >= 0 Then
            node.Nodes(index).Remove()
        End If
    End Sub

    Private Sub saveAdaptation(ByVal treeNode As TreeNode)
        Try
            While treeNode.Tag.getIsOriginal() = 1
                Dim obj As Component = treeNode.Tag
                obj.setVersion(obj.getVersion() + 1)
                obj.update("version")
                obj.setRef(obj.getRef() & "_ADAP_" & obj.getVersion())
                setInitInfo(obj, 0, mainForm.currentUser.getLogin(), Today, 0) ' version adaptée
                obj.insert()
                obj.setIsOriginal(0)
                obj.updateAll()
                treeNode.Tag = obj
                treeNode.Nodes.Find("ref", True)(0).Text = "ref : " & obj.getRef()
                If Not treeNode.Parent Is Nothing Then
                    treeNode = treeNode.Parent
                End If
            End While
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub findButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles findButton.Click
        chooseItemZone.Enabled = True
        itemsTreeView.Nodes.Clear()
        Dim tableName As String = treeView.SelectedNode.Parent.Tag.tableName
        Dim treeNode As TreeNode = loadItemsListToTree(tableName)
        itemsTreeView.Nodes.Add(treeNode)
    End Sub

    Public Function loadItemsListToTree(ByVal itemTableName As String) As TreeNode
        Dim connectionString As String
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim sql As String
        Dim reader As SqlDataReader
        Dim rootNode = New TreeNode()
        Dim source As String = System.Net.Dns.GetHostEntry("cre2-w01526").AddressList(0).ToString
        connectionString = "Data Source=" & source & ";Initial Catalog=AlternatorDatabase; Integrated Security=SSPI;"
        sql = "SELECT * FROM " & itemTableName
        connection = New SqlConnection(connectionString)
        rootNode.Text = "available items :"
        rootNode.Name = "root"
        Try
            connection.Open()
            command = New SqlCommand(sql, connection)
            reader = command.ExecuteReader()
            Try
                While reader.Read()
                    Dim obj As New Component
                    obj = obj.getObjectByKey(reader(0), columnNameToFunctionName(itemTableName), itemTableName)
                    Dim node As TreeNode = buidTreeNodeFromTable(obj)
                    node.Text = getLabelFormName(obj.tableName)
                    node.Name = getLabelFormName(obj.tableName)
                    node.Tag = obj
                    rootNode.Nodes.Add(node)
                End While
                command.Dispose()
                connection.Close()
            Finally
                reader.Close()
            End Try
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        Return rootNode
    End Function

    Public Function isDouble(ByVal objString As String) As Boolean
        Dim rg As New Regex("[0-9]+(\,[0-9]+)?", RegexOptions.IgnoreCase)
        Dim matches As MatchCollection = rg.Matches(objString)
        If matches.Count = 0 Then
            Return False
        End If
        If matches.Count = 1 And matches.Item(0).Length = objString.Length Then
            Return True
        End If
        Return False
    End Function

    Public Function getDataType(ByVal tableName As String, ByVal fieldName As String) As String
        Dim dataType As String = ""
        Dim connectionString As String
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim sql As String
        Dim reader As SqlDataReader
        Dim source As String = System.Net.Dns.GetHostEntry("cre2-w01526").AddressList(0).ToString
        connectionString = "Data Source=localhost;Initial Catalog=AlternatorDatabase; Integrated Security=SSPI;"
        sql = "select DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG = 'AlternatorDatabase' and TABLE_NAME = '" & tableName & "' AND COLUMN_NAME = '" & fieldName & "'"
        connection = New SqlConnection(connectionString)
        Try
            connection.Open()
            command = New SqlCommand(sql, connection)
            reader = command.ExecuteReader()
            Try
                reader.Read()
                dataType = reader(0)
                command.Dispose()
                connection.Close()
            Finally
                reader.Close()
            End Try
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        Return dataType
    End Function

    Public Function checkValueField(ByVal tableName As String, ByVal fieldName As String, ByVal value As String) As Boolean
        Dim ok As Boolean = True
        Dim dataType As String = getDataType(tableName, toDataBaseColumnName(fieldName))
        If dataType = "real" Then
            Dim result As Double
            If value = "0" Then
                ok = True
            Else
                Double.TryParse(value, result)
                If result = 0 Then
                    ok = False
                End If
            End If
        End If
        If dataType = "int" And Not IsNumeric(value) Then
            ok = False
        End If
        Return ok
    End Function

    Function getRightTabPage() As Control
        Return rightTabPage
    End Function

    Private Sub itemsTreeView_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles itemsTreeView.AfterSelect
        If e.Node.Name <> "root" Then
            Dim obj As Object = e.Node.Tag
            If obj Is Nothing Then
                obj = e.Node.Parent.Tag
            End If
            valueTextBox.Text = obj.getRef()
        End If
    End Sub

    Private Sub closeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeButton.Click
        Dim parentLeftControl As Control = leftTabPage.Parent
        parentLeftControl.Controls.Remove(leftTabPage)
        Dim parentRightControl As Control = rightTabPage.Parent
        parentRightControl.Controls.Remove(rightTabPage)
    End Sub

    Private Sub magnetAddButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles magnetAddButton.Click
        Dim selectedNode As TreeNode = treeView.SelectedNode
        Dim rotor As Rotor = selectedNode.Parent.Parent.Tag
        Dim magnetRef As String = selectedNode.Name
        Dim rotorMagnet As RotorMagnet = rotor.getRotorMagnet(magnetRef)
        rotorMagnet.setQuantity(rotorMagnet.getQuantity() + 1)
        rotorMagnet.update()

        ' update treeview
        selectedNode.Text = "Magnet Ref : " & magnetRef & " quantity : " & rotorMagnet.getQuantity()
        If rotorMagnet.getQuantity > 1 Then
            magnetSubButton.Enabled = True
        End If
    End Sub

    Private Sub magnetSubButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles magnetSubButton.Click
        Dim selectedNode As TreeNode = treeView.SelectedNode
        Dim rotor As Rotor = selectedNode.Parent.Parent.Tag
        Dim magnetRef As String = selectedNode.Name
        Dim rotorMagnet As RotorMagnet = rotor.getRotorMagnet(magnetRef)
        rotorMagnet.setQuantity(rotorMagnet.getQuantity() - 1)
        rotorMagnet.update()

        ' update treeview
        selectedNode.Text = "Magnet Ref : " & magnetRef & " quantity : " & rotorMagnet.getQuantity()
        If rotorMagnet.getQuantity = 1 Then
            magnetSubButton.Enabled = False
        End If
    End Sub

    Private Sub listMagnetButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listMagnetButton.Click
        If listMagnetButton.Text = "List..." Then
            chooseItemZone.Enabled = True
            itemsTreeView.Nodes.Clear()
            Dim tableName As String = "magnet"
            Dim treeNode As TreeNode = loadItemsListToTree(tableName)
            itemsTreeView.Nodes.Add(treeNode)
            listMagnetButton.Text = "Add"
        Else
            Dim rotor As Rotor = treeView.SelectedNode.Parent.Tag
            If rotor Is Nothing Then
                rotor = treeView.SelectedNode.Parent.Parent.Tag
            End If

            Dim manget As Magnet = itemsTreeView.SelectedNode.Parent.Tag
            If manget Is Nothing Then
                manget = itemsTreeView.SelectedNode.Tag
            End If
            Dim rotorMagnet As RotorMagnet = rotor.getRotorMagnet(manget.getRef())
            If rotorMagnet Is Nothing Then
                rotorMagnet = New RotorMagnet(rotor.getRef(), manget.getRef())
                rotorMagnet.setQuantity(1)
                If rotorMagnet.insert() Then
                    ' update treeView
                    Dim node As New TreeNode
                    node.Text = "Magnet Ref : " & rotorMagnet.getMagnetRef() & " quantity : " & rotorMagnet.getQuantity()
                    node.Name = rotorMagnet.getMagnetRef()
                    node.Tag = rotorMagnet
                    If treeView.SelectedNode.Text = "magnets" Then
                        treeView.SelectedNode.Nodes.Add(node)
                    Else
                        treeView.SelectedNode.Parent.Nodes.Add(node)
                    End If
                End If
            Else
                rotorMagnet.setQuantity(rotorMagnet.getQuantity() + 1)
                rotorMagnet.update()

                ' update TreeView
                If treeView.SelectedNode.Text = "magnets" Then
                    For i As Integer = 0 To treeView.SelectedNode.Nodes.Count - 1 Step 1
                        If treeView.SelectedNode.Nodes(i).Name = rotorMagnet.getMagnetRef Then
                            treeView.SelectedNode.Nodes(i).Text = "Magnet Ref : " & rotorMagnet.getMagnetRef() & " quantity : " & rotorMagnet.getQuantity()
                            treeView.SelectedNode.Nodes(i).Tag = rotorMagnet
                        End If
                    Next
                Else
                    treeView.SelectedNode.Tag = rotorMagnet
                    treeView.SelectedNode.Text = "Magnet Ref : " & rotorMagnet.getMagnetRef() & " quantity : " & rotorMagnet.getQuantity()
                End If

            End If
        End If
    End Sub

    Private Sub deleteMangetButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deleteMagnetButton.Click
        Dim rotorMagnet As RotorMagnet = treeView.SelectedNode.Tag
        If rotorMagnet.delete() Then
            ' update tree view
            treeView.Nodes.Remove(treeView.SelectedNode)
        End If
    End Sub

    Private Sub leftTabPage_onSizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles leftTabPage.SizeChanged
        If Not treeView Is Nothing And Not modifyZone Is Nothing And Not itemsTreeView Is Nothing Then
            treeView.Location = New System.Drawing.Point(leftTabPage.Left, leftTabPage.Top)
            treeView.Width = leftTabPage.Width - 20
            treeView.Height = (leftTabPage.Height / 5) * 3

            modifyZone.Location = New System.Drawing.Point(treeView.Left, treeView.Bottom)
            modifyZone.Width = leftTabPage.Width - 20
            modifyZone.Height = (leftTabPage.Height / 10) * 1.25

            magnetModifyZone.Location = modifyZone.Location
            magnetModifyZone.Size = modifyZone.Size
            deleteMagnetButton.Location = New System.Drawing.Point(magnetModifyZone.Right - deleteMagnetButton.Width - 10, 20)
            magnetSubButton.Location = New System.Drawing.Point(magnetModifyZone.Right - 2 * magnetSubButton.Width - 13, 20)
            magnetAddButton.Location = New System.Drawing.Point(magnetModifyZone.Right - 3 * magnetAddButton.Width - 16, 20)


            listMagnetButton.Location = New System.Drawing.Point(magnetModifyZone.Width - 10 - listMagnetButton.Width, magnetModifyZone.Height - 10 - listMagnetButton.Height)

            modifyButton.Location = New System.Drawing.Point(modifyZone.Width - 20 - modifyButton.Width, modifyZone.Height - 10 - modifyButton.Height)
            findButton.Location = New System.Drawing.Point(modifyButton.Left - findButton.Width - 10, modifyButton.Top)

            chooseItemZone.Location = New System.Drawing.Point(modifyZone.Left, modifyZone.Bottom)
            chooseItemZone.Width = leftTabPage.Width - 20
            chooseItemZone.Height = (leftTabPage.Height / 5) * 1

            closeButton.Location = New System.Drawing.Point(chooseItemZone.Right - closeButton.Width, chooseItemZone.Bottom)
        End If
    End Sub

    Private Sub rightTabPage_onSizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rightTabPage.SizeChanged
        If Not descriptionZone Is Nothing And Not descriptionText Is Nothing Then
            descriptionZone.Location = New System.Drawing.Point(0, 0)
            descriptionZone.Width = rightTabPage.Width - 15
            descriptionZone.Height = (rightTabPage.Height / 10) * 1
            descriptionText.Location = New System.Drawing.Point(5, 15)
            descriptionText.Width = descriptionZone.Width - 10
            descriptionText.Height = descriptionZone.Height - 20
            illustrationZone.Location = New System.Drawing.Point(descriptionZone.Left, descriptionZone.Bottom)
            illustrationZone.Width = descriptionZone.Width
            illustrationZone.Height = (rightTabPage.Height / 10) * 7.55
        End If
    End Sub

    Private Sub createShapes(ByVal node As TreeNode)
        Dim excelApp As Excel.Application
        Dim excelWorkSheet As Worksheet

        Dim excelBook As Workbook
        excelApp = New Excel.Application
        excelBook = excelApp.Workbooks.Open("E:\Documents and Settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\calcul\Stator_winding_design_tool.xls", Password:="aquarious")
        If excelBook.HasPassword = False Then
            excelBook.Password = "aquarious"
        End If
        excelWorkSheet = excelBook.Worksheets("Input Data")
        illustrationPicture.Visible = False
        illustrationSlot.Visible = True

        If Not myGraphic Is Nothing Then
            myGraphic.Clear(System.Drawing.Color.FromKnownColor(KnownColor.Control))
        Else
            myGraphic = illustrationSlot.CreateGraphics
        End If

        myGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        FillData(excelWorkSheet)
        drawingSlot(excelWorkSheet, excelBook, myGraphic)


        excelBook.Save()
        excelBook.Close(False)
        excelApp.Quit()

    End Sub

    Private Sub drawingSlot(ByVal source As Excel.Worksheet, ByVal excelBook As Excel.Workbook, ByVal graphic As System.Drawing.Graphics)
        Dim echX As Double
        Dim echY As Double
        Dim sod As Double
        Dim sid As Double
        Dim dfenc As Double
        Dim X0 As Integer
        Dim Y0 As Integer
        Dim sn As Double
        Dim so As Double
        Dim soh As Double
        Dim swt As Double
        Dim bsw As Double
        Dim tsw As Double
        Dim tn As Integer
        Dim tnold As Integer
        Dim pwn As Integer
        Dim pwnold As Integer
        Dim wdmax As Double
        Dim hslot As Double
        Dim pside As Double
        Dim X1 As Double
        Dim X2 As Double
        Dim X3 As Double
        Dim Y1 As Double
        Dim Y2 As Double
        Dim pts(0 To 4, 0 To 2) As Single
        echX = 20
        echY = 20
        X0 = 700
        Y0 = 1550 + 200
        sod = source.Range("sod").Value
        dfenc = excelBook.Worksheets("Data processing").Range("dfenc").Value
        sid = source.Range("sid").Value
        so = source.Range("so").Value
        sn = source.Range("sn").Value
        soh = source.Range("soh").Value
        bsw = source.Range("bsw").Value
        tsw = source.Range("tsw").Value
        wdmax = excelBook.Worksheets("Slot definition for parallel S").Range("wdmax").Value
        tn = source.Range("tn").Value
        tnold = source.Range("tnold").Value
        pwn = source.Range("pwn").Value
        pwnold = source.Range("pwnold").Value
        swt = source.Range("swt").Value
        hslot = excelBook.Worksheets("Slot definition for parallel S").Range("hslot").Value
        pside = source.Range("pside").Value
        Dim Pi = 4 * Math.Atan(1)
        Dim tana = (tsw - bsw) / 2 / hslot
        'Diamètre(extérieur)
        X1 = X0 - sod / 2 * Math.Sin(Pi / sn) * echX
        X3 = X0 + sod / 2 * Math.Sin(Pi / sn) * echY
        X2 = X0
        Y1 = Y0 - sod / 2 * Math.Cos(Pi / sn) * echX
        Dim Y3 = Y1
        Y2 = Y0 - sod / 2 * echX
        Dim X111 = X0 - sod / 2 * Math.Sin(Pi / sn / 2) * echX
        Dim X311 = X0 + sod / 2 * Math.Sin(Pi / sn / 2) * echY
        Dim Y111 = Y0 - sod / 2 * Math.Cos(Pi / sn / 2) * echX
        'Flanc gauche
        Dim X4 = X0 - sid / 2 * Math.Sin(Pi / sn) * echX
        Dim Y4 = Y0 - sid / 2 * Math.Cos(Pi / sn) * echY
        'Flanc droite
        Dim X5 = X0 + sid / 2 * Math.Sin(Pi / sn) * echX
        Dim Y5 = Y4
        'Diamètre intérieur gauche
        Dim X6 = X0 - sid / 2 * Math.Sin(Math.Atan(so / sid)) * echX
        Dim Y6 = Y0 - sid / 2 * Math.Cos(Math.Atan(so / sid)) * echY
        'Diamètre intérieur droite
        Dim X7 = X0 + sid / 2 * Math.Sin(Math.Atan(so / sid)) * echX
        Dim Y7 = Y6
        'Semelle gauche
        Dim X8 = X6
        Dim Y8 = Y6 - soh * echX
        'Semelle droite
        Dim X9 = X7
        Dim Y9 = Y8
        'Flanc Semelle gauche
        Dim X10 = X0 - (sid / 2 + soh * 2) * Math.Sin(Math.Atan(bsw / (sid + 2 * soh * 2))) * echX
        Dim Y10 = Y0 - (sid / 2 + soh * 2) * Math.Cos(Math.Atan(bsw / (sid + 2 * soh * 2))) * echY
        'Flanc Semelle droite
        Dim X11 = X0 + (sid / 2 + soh * 2) * Math.Sin(Math.Atan(bsw / (sid + 2 * soh * 2))) * echX
        Dim Y11 = Y10
        'Fond encoche gauche
        Dim X12 = X0 - (dfenc / 2) * Math.Sin(Math.Atan(tsw / dfenc)) * echX
        Dim Y12 = Y0 - (dfenc / 2) * Math.Cos(Math.Atan(tsw / dfenc)) * echY
        'Fond encoche droite
        Dim X13 = X0 + (dfenc / 2) * Math.Sin(Math.Atan(tsw / dfenc)) * echX
        Dim Y13 = Y12
        'Fond encoche centre
        Dim X14 = X0
        Dim Y14 = Y0 - dfenc / 2 * echX
        Dim listPoints(0 To 15) As System.Drawing.Point
        listPoints(0) = New System.Drawing.Point(X3, Y3)
        listPoints(1) = New System.Drawing.Point(X311, Y111)
        listPoints(2) = New System.Drawing.Point(X2, Y2)
        listPoints(3) = New System.Drawing.Point(X111, Y111)
        listPoints(4) = New System.Drawing.Point(X1, Y1)
        listPoints(5) = New System.Drawing.Point(X4, Y4)
        listPoints(6) = New System.Drawing.Point(X6, Y6)
        listPoints(7) = New System.Drawing.Point(X8, Y8)
        listPoints(8) = New System.Drawing.Point(X10, Y10)
        listPoints(9) = New System.Drawing.Point(X12, Y12)
        listPoints(10) = New System.Drawing.Point(X14, Y14)
        listPoints(11) = New System.Drawing.Point(X13, Y13)
        listPoints(12) = New System.Drawing.Point(X11, Y11)
        listPoints(13) = New System.Drawing.Point(X9, Y9)
        listPoints(14) = New System.Drawing.Point(X7, Y7)
        listPoints(15) = New System.Drawing.Point(X5, Y5)
        Dim minX As Double = Double.MaxValue
        Dim minY As Double = Double.MaxValue
        For i As Integer = 0 To 15 Step 1
            If listPoints(i).X < minX Then
                minX = listPoints(i).X
            End If
            If listPoints(i).Y < minY Then
                minY = listPoints(i).Y
            End If
        Next
        For i As Integer = 0 To 15 Step 1
            listPoints(i).X = listPoints(i).X - minX + rightTabPage.Width / 2 - 100
            listPoints(i).Y = listPoints(i).Y - minY + 100
        Next

        Dim listPointsEncB(0 To 3) As System.Drawing.Point
        listPointsEncB(0) = New System.Drawing.Point(listPoints(11).X, listPoints(11).Y)
        listPointsEncB(1) = New System.Drawing.Point(listPoints(9).X, listPoints(9).Y)
        listPointsEncB(2) = New System.Drawing.Point(listPoints(8).X, listPoints(8).Y)
        listPointsEncB(3) = New System.Drawing.Point(listPoints(12).X, listPoints(12).Y)
        Dim listPointsIsolant(0 To 3) As System.Drawing.Point
        listPointsIsolant(0) = New System.Drawing.Point(listPoints(11).X - swt * echX, listPoints(11).Y + swt * echX)
        listPointsIsolant(1) = New System.Drawing.Point(listPoints(9).X + swt * echX, listPoints(9).Y + swt * echX)
        listPointsIsolant(2) = New System.Drawing.Point(listPoints(8).X + swt * echX, listPoints(8).Y - swt * echX)
        listPointsIsolant(3) = New System.Drawing.Point(listPoints(12).X - swt * echX, listPoints(12).Y - swt * echX)
        Dim listPointsFond(0 To 3) As System.Drawing.Point
        listPointsFond(0) = New System.Drawing.Point(listPoints(0).X + 50, listPoints(0).Y - 50)
        listPointsFond(1) = New System.Drawing.Point(listPoints(4).X - 50, listPoints(4).Y - 50)
        listPointsFond(2) = New System.Drawing.Point(listPoints(4).X - 50, listPoints(5).Y + 50)
        listPointsFond(3) = New System.Drawing.Point(listPoints(0).X + 50, listPoints(15).Y + 50)

        graphic.FillPolygon(Brushes.WhiteSmoke, listPointsFond)
        graphic.FillPolygon(Brushes.Green, listPointsEncB)
        graphic.FillPolygon(Brushes.White, listPointsIsolant)
        graphic.FillPolygon(Brushes.Aqua, listPoints)

        Dim kligne = 1
        Dim kcol = 1
        Dim sens = 1
        Dim Xprev = X12 + (swt + tana * wdmax / 2) * echX
        For j As Integer = 1 To pwn Step 1
            For i As Integer = 1 To tn Step 1
                Dim Y As Double
                Dim X As Double
                Dim h_ligne As Double
                Dim w_ligne As Double
                Dim Xdeb As Double
                Dim Xfin As Double
                Dim extreme As Double
                Dim Xinit1 As Double
                Dim Xinit2 As Double
                Dim Xtest As Double
                If pside > 1.5 Then
                    Y = Y12 + (swt + (i - 1) * wdmax) * echX
                    X = X12 + (swt + tana * (1 + 2 * (i - 1)) * wdmax / 2 + (j - 1) * wdmax) * echX
                Else
                    h_ligne = (swt + (kligne - 1) * wdmax / 2 / Math.Tan(Pi / 6))
                    w_ligne = (tsw - swt - h_ligne * 2 * tana)
                    Y = Y12 + (swt + (kligne - 1) * wdmax / 2 / Math.Tan(Pi / 6)) * echX
                    Xdeb = X12 + (swt + tana * (1 + 2 * (kligne - 1)) * wdmax / 2) * echX
                    Xfin = Xdeb + (tsw - swt - h_ligne * 2 * tana) * echX
                    If (kcol * kligne = 1) Then
                        X = Xdeb
                    Else
                        If (extreme * sens < 0) Then
                            Xinit1 = Xprev + sens * (1 - extreme / 2) * wdmax * echX
                            Xinit2 = Xprev + sens * (2 - extreme / 2) * wdmax * echX
                            If Xinit1 < Xfin Then
                                X = Xinit1
                            Else
                                X = Xinit2
                            End If
                        Else
                            If (extreme * sens > 0) Then
                                Xinit1 = Xprev + sens * (0 - extreme / 2) * wdmax * echX
                                Xinit2 = Xprev + sens * (1 - extreme / 2) * wdmax * echX
                                If Xinit1 > (Xdeb - 3) Then
                                    X = Xinit1
                                Else
                                    X = Xinit2
                                End If
                            Else
                                X = Xprev + sens * (1 - extreme / 2) * wdmax * echX
                            End If
                        End If
                    End If
                    Xprev = X
                    If sens > 0 Then
                        Xtest = (Xprev + 2 * wdmax * echX)
                        If Xtest > Xfin Then
                            kligne = kligne + 1
                            kcol = 1
                            extreme = 1
                            sens = -1
                        Else
                            kligne = kligne
                            kcol = kcol + 1
                            extreme = 0
                        End If
                    Else
                        Xtest = (Xprev - 1 * wdmax * echX)
                        If Xtest < Xdeb Then
                            kligne = kligne + 1
                            kcol = 1
                            sens = 1
                            extreme = 1
                        Else
                            kligne = kligne
                            kcol = kcol + 1
                            extreme = 0
                        End If
                    End If
                End If
                Dim rec As New System.Drawing.Rectangle()
                rec.Width = wdmax * echX
                rec.Height = wdmax * echX
                rec.X = X - minX + rightTabPage.Width / 2 - 100
                rec.Y = Y - minY + 100
                graphic.FillEllipse(Brushes.Red, rec)
            Next
        Next
    End Sub

    Private Sub FillData(ByRef ws As Excel.Worksheet)
        Dim tempoObj As Alternator = obj.getObjectByKey(obj.getRef, "Alternator", "alternator")
        ws.Range("D10").Value = tempoObj.getRef()
        ws.Range("D11").Value = tempoObj.getVoltage()
        ws.Range("D12").Value = tempoObj.getNominalOutput()
        ws.Range("D13").Value = tempoObj.getElectricalDefinition()
        ws.Range("D14").Value = tempoObj.getPolePairsNumber()

        Dim stator As New Stator
        stator = stator.getObjectByKey(tempoObj.getStator(), "Stator", "stator")
        Dim statorCore As New StatorCore
        statorCore = statorCore.getObjectByKey(stator.getStatorCore(), "StatorCore", "stator_core")
        ws.Range("sod").Value = statorCore.getOuterDiameter()
        ws.Range("sl").Value = statorCore.getStackLength()
        ws.Range("D21").Value = statorCore.getLaminationSheetThickness()
        ws.Range("sid").Value = statorCore.getInnerDiameter()
        Dim slotDef As New SlotDefinition
        slotDef = slotDef.getObjectByKey(stator.getSlotDefinition(), "SlotDefinition", "slot_definition")
        ws.Range("sn").Value = slotDef.getSlotNumber()
        ws.Range("pside").Value = slotDef.getSlotWithParallelSides()
        ws.Range("tw").Value = slotDef.getTeethWidth()
        ws.Range("tsh").Value = slotDef.getTeethShoeHeight()
        ws.Range("bsr").Value = slotDef.getBottomSlotCornerRadius()
        ws.Range("soh").Value = slotDef.getSlotOpeningHeight()
        Dim statorCoil As New StatorCoil
        statorCoil = statorCoil.getObjectByKey(stator.getStatorCoil(), "StatorCoil", "stator_coil")
        ws.Range("D38").Value = statorCoil.getWindingType()
        ws.Range("D42").Value = statorCoil.getPhaseNumber()
        ws.Range("tn").Value = statorCoil.getTurnsNumberPerPhase()
        ws.Range("pwn").Value = statorCoil.getParallelWiresNumber()
        ws.Range("wd").Value = statorCoil.getWireDiameter()
    End Sub

End Class

Public Class Searching
    Inherits mainForm
    Private leftTabPage As TabPage ' for the entering test
    Private rightTabPage As TabPage ' for results display
    Private WithEvents testTreeView As TreeView ' for the test choices
    Private WithEvents testValue As System.Windows.Forms.TextBox
    Private WithEvents addButton As System.Windows.Forms.Button
    Private addValueZone As System.Windows.Forms.GroupBox
    Private WithEvents launchButton As System.Windows.Forms.Button
    Private WithEvents testLabel As System.Windows.Forms.Label
    Private searchingAlter As Alternator
    Private WithEvents resultGrid As System.Windows.Forms.DataGridView
    Private WithEvents ctMenu As System.Windows.Forms.ContextMenuStrip


    Sub New()
        ' initialize the tab pages
        leftTabPage = New TabPage("Search")
        rightTabPage = New TabPage("Results")

        ' initialize the tree view
        testTreeView = New TreeView()
        testTreeView.Location = New System.Drawing.Point(leftTabPage.Left, leftTabPage.Top)
        testTreeView.Width = mainForm.leftTabControl.Width - 10
        testTreeView.Height = 285
        testTreeView.CheckBoxes = True
        testTreeView.HideSelection = False

        ' initialize the adding value zone
        addValueZone = New System.Windows.Forms.GroupBox()
        addValueZone.Text = "Add a value"
        addValueZone.Location = New System.Drawing.Point(testTreeView.Left, testTreeView.Bottom)
        addValueZone.Width = mainForm.leftTabControl.Width - 10
        addValueZone.Height = 100

        testLabel = New System.Windows.Forms.Label
        testLabel.Text = ""
        testLabel.Location = New System.Drawing.Point(10, 20)
        testValue = New System.Windows.Forms.TextBox()
        testValue.Location = New System.Drawing.Point(10 + testLabel.Width, 20)
        testValue.Width = 100

        addButton = New System.Windows.Forms.Button()
        'addButton.Image = My.Resources.add
        addButton.Text = "+"
        addButton.Location = New System.Drawing.Point(testValue.Right + 10, 20)
        addButton.Width = 22
        addButton.Height = 22
        addButton.TextAlign = ContentAlignment.MiddleCenter
        addButton.Enabled = False


        launchButton = New System.Windows.Forms.Button()
        launchButton.Text = "Launch"
        launchButton.AutoSize = True
        launchButton.Dock = DockStyle.Bottom
        launchButton.Enabled = False

        ' notice zone
        Dim noticeZone As New System.Windows.Forms.GroupBox
        noticeZone.Location = New System.Drawing.Point(addValueZone.Left, addValueZone.Bottom)
        noticeZone.Width = mainForm.leftTabControl.Width - 10
        Dim noticeLabel As New System.Windows.Forms.Label
        noticeLabel.Location = New System.Drawing.Point(10, 10)
        noticeLabel.Text = "Notice : Firstly click into tree view's line to choose the research's criteria, then enter its value. To add this value, click + button or check in checkbox"
        noticeLabel.Width = mainForm.leftTabControl.Width - 30
        noticeLabel.Height = noticeZone.Height - 20
        noticeZone.Controls.Add(noticeLabel)

        ' add to control
        leftTabPage.Controls.Add(testTreeView)
        leftTabPage.Controls.Add(addValueZone)

        addValueZone.Controls.Add(testValue)
        addValueZone.Controls.Add(addButton)
        addValueZone.Controls.Add(launchButton)
        addValueZone.Controls.Add(testLabel)
        leftTabPage.Controls.Add(noticeZone)
    End Sub

    Public Function getLeftTabPage() As TabPage
        Return leftTabPage
    End Function

    Public Function getRightTabPage() As TabPage
        Return rightTabPage
    End Function

    Private Sub addButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addButton.Click
        saveCriteria()
    End Sub

    Public Sub loadTree()
        searchingAlter = New Alternator()
        testTreeView.Nodes.Add(buidTreeNodeFromTable(searchingAlter))
    End Sub

    Public Function buildRequest(ByVal sql As String, ByVal treeNode As TreeNode) As String

        Return sql
    End Function

    Private Sub testTreeView_AfterCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles testTreeView.AfterCheck
        Dim obj As Object = e.Node.Tag
        If obj Is Nothing Then
            obj = e.Node.Parent.Tag
            If e.Node.Checked Then
                Dim value As Object = obj.getAttribute(columnNameToFunctionName(e.Node.Name))

                If testValue.Text = "" Then
                    MsgBox("Enter a value before checking", vbCritical)
                    e.Node.Checked = False
                ElseIf value Is Nothing Then
                    saveCriteria()
                ElseIf value.ToString = "0" Then
                    saveCriteria()
                End If
            Else
                obj.setAttribute(columnNameToFunctionName(e.Node.Name), Nothing)
                e.Node.Text = e.Node.Name
            End If
        End If
    End Sub

    Private Sub testTreeView_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles testTreeView.AfterSelect
        Dim obj As Object = e.Node.Tag
        testValue.Text = ""
        If obj Is Nothing Then
            obj = e.Node.Parent.Tag
            testLabel.Text = e.Node.Name & " : "
            addButton.Enabled = True
        Else
            addButton.Enabled = False
            testLabel.Text = "Choose a criteria"
        End If

    End Sub

    Private Sub saveCriteria()
        Dim selectedNode As TreeNode = testTreeView.SelectedNode
        Dim obj As Object = selectedNode.Parent.Tag
        obj.setAttribute(columnNameToFunctionName(selectedNode.Name), testValue.Text)
        Dim value As Object = obj.getAttribute(columnNameToFunctionName(selectedNode.Name))
        If Not value Is Nothing And Not value.ToString = "0" Then ' setAttribute success
            selectedNode.Text = selectedNode.Name & " : " & obj.getAttribute(columnNameToFunctionName(selectedNode.Name))
            selectedNode.Checked = True
            If selectedNode.Name = "ref" And Not selectedNode.Parent.Parent Is Nothing Then
                Dim parentObj As Object = selectedNode.Parent.Parent.Tag
                parentObj.setAttribute(columnNameToFunctionName(obj.tableName), testValue.Text)
            End If
            selectedNode.Parent.Tag = obj
            If launchButton.Enabled = False Then
                launchButton.Enabled = True
            End If
        Else
            selectedNode.Checked = False
        End If
    End Sub

    Private Sub launchButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles launchButton.Click
        Dim sql As String = "SELECT alternator.ref as 'Reference'," & _
            "alternator.version as 'Version'," & _
            "alternator.editor as 'Editor'," & _
            "alternator.modified_date as 'Modified Date'," & _
            "CASE WHEN alternator.is_original = 1" & _
            "THEN 'yes' " & _
            "ELSE 'no' " & _
            "END AS 'Original'," & _
            "alternator.nominal_output AS 'Nominal Output'," & _
            "alternator.electrical_definition AS 'Electrical Definition'," & _
            "alternator.pole_pairs_number AS 'Pole pairs number' " & _
            "FROM alternator "
        Dim listTables(0 To 50) As String
        Dim index As Integer = 0
        getJointTables(testTreeView.Nodes(0), listTables, index)
        addJointTables(testTreeView.Nodes(0), listTables, sql)
        sql += " WHERE (alternator.is_original = 1 OR alternator.editor = '" & mainForm.currentUser.getLogin() & "') AND "
        addConditions(testTreeView.Nodes(0), sql)
        sql = sql.Remove(sql.Length - 4, 4)
        Dim obj As New Component

        exucuteRequest(sql)
        rightTabPage.Controls.Clear()
        If Not resultGrid Is Nothing Then
            With resultGrid
                .RowHeadersVisible = False
                .ColumnHeadersHeight = 35
                .AutoSize = True
                .Dock = DockStyle.Fill
                .ReadOnly = True
            End With
            rightTabPage.Controls.Add(resultGrid)
        End If
    End Sub

    Private Sub getJointTables(ByVal treeNode As TreeNode, ByRef listTables As String(), ByRef index As Integer)
        Dim nberChildren As Integer = treeNode.Nodes.Count
        For i As Integer = 0 To nberChildren - 1 Step 1
            If treeNode.Nodes(i).Checked Then
                Dim tempo As TreeNode = treeNode
                While Not tempo.Tag.tableName = "alternator"
                    If isMember(listTables, tempo.Tag.tableName) = False Then
                        listTables(index) = tempo.Tag.tableName
                        index += 1
                    End If
                    tempo = tempo.Parent
                End While
            End If
            getJointTables(treeNode.Nodes(i), listTables, index)
        Next
    End Sub

    Private Sub addJointTables(ByVal treeNode As TreeNode, ByVal listTables As String(), ByRef sql As String)
        Dim nberChildren As Integer = treeNode.Nodes.Count
        For i As Integer = 0 To nberChildren - 1 Step 1
            Dim obj As TreeNode = treeNode.Nodes(i)
            If isMember(listTables, tableNameToFunctionName(obj.Name)) Then
                sql += " LEFT JOIN " & tableNameToFunctionName(obj.Name) & " ON " & treeNode.Tag.tableName & "." & tableNameToFunctionName(obj.Name) & " = " & tableNameToFunctionName(obj.Name) & ".ref"
            End If
        Next
        For i As Integer = 0 To nberChildren - 1 Step 1
            addJointTables(treeNode.Nodes(i), listTables, sql)
        Next
    End Sub

    Private Sub addConditions(ByVal treeNode As TreeNode, ByRef sql As String)
        Dim nberChildren As Integer = treeNode.Nodes.Count
        Dim obj As Object = treeNode.Tag
        For i As Integer = 0 To nberChildren - 1 Step 1
            If treeNode.Nodes(i).Checked Then
                Dim value As Object = obj.getAttribute(columnNameToFunctionName(treeNode.Nodes(i).Name))
                If value.GetType().ToString = "System.Integer" Then
                    sql += obj.tableName & "." & tableNameToFunctionName(treeNode.Nodes(i).Name) & " = " & value.ToString.Replace(",", ".")
                ElseIf value.GetType().ToString = "System.Double" Then
                    sql += "abs(" & obj.tableName & "." & tableNameToFunctionName(treeNode.Nodes(i).Name) & " - " & value.ToString.Replace(",", ".") & ") <= 1"
                Else
                    sql += obj.tableName & "." & tableNameToFunctionName(treeNode.Nodes(i).Name) & " LIKE '%" & value & "%'"
                End If
                sql += " AND "
            End If
            addConditions(treeNode.Nodes(i), sql)
        Next
    End Sub

    Private Sub exucuteRequest(ByVal sql As String)
        Dim connectionString As String
        Dim connection As SqlConnection

        connectionString = "Data Source=VES-CRE-W01526;Initial Catalog=AlternatorDatabase; Integrated Security=SSPI;"
        connection = New SqlConnection(connectionString)

        Try
            Console.Write(sql)
            connection.Open()
            Dim ds As New DataSet
            Dim dscmd As New SqlDataAdapter(sql, connection)
            dscmd.Fill(ds)
            resultGrid = New System.Windows.Forms.DataGridView
            resultGrid.DataSource = ds.Tables(0)
            connection.Close()
        Catch e As Exception
        End Try
    End Sub

    Private Sub resultGrid_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles resultGrid.MouseDown
        If e.Button = System.Windows.Forms.MouseButtons.Right Then
            'Dim resultGridCell As DataGridCell = resultGrid.CurrentCell
            Dim d As DataGridViewCell = resultGrid.CurrentCell
            ctMenu = New ContextMenuStrip
            ctMenu.Items.Add("Adaptation")
            ctMenu.Items.Add("Modifier")
            ctMenu.Items.Add("Delete")
            Dim calculDebit As New ToolStripDropDownButton("Calcul...", Nothing, Nothing, "Calcul")
            ctMenu.Items.Add(calculDebit)
            Dim calculMenu As New ContextMenuStrip
            calculMenu.Items.Add("Debit")
            calculDebit.DropDown = calculMenu
            Dim alterRef As String = resultGrid.Rows(resultGrid.CurrentCell.RowIndex).Cells(0).Value
            Dim alter As New Component
            alter = alter.getObjectByKey(alterRef, "Alternator", "alternator")

            If mainForm.currentUser.getUserRight() = 2 Then
                If alter.getIsOriginal() = 1 Then
                    ctMenu.Items(1).Enabled = False
                    ctMenu.Items(2).Enabled = False
                End If
            End If

            If alter.getIsOriginal() = 0 Then
                ctMenu.Items(0).Enabled = False
            End If

            AddHandler ctMenu.Items(0).Click, AddressOf searchingResultAdapClick
            AddHandler ctMenu.Items(1).Click, AddressOf searchingResultModifClick
            AddHandler ctMenu.Items(2).Click, AddressOf searchingResultDeleteClick
            AddHandler calculMenu.Items(0).Click, AddressOf searchingResultCalculDebitClick
            d.ContextMenuStrip = ctMenu
        End If

    End Sub

    Private Sub searchingResultAdapClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim alterRef As String = resultGrid.Rows(resultGrid.CurrentCell.RowIndex).Cells(0).Value
        If alterRef <> "" Then
            Dim alter As New Component
            alter = alter.getObjectByKey(alterRef, "Alternator", "alternator")
            alter.setVersion(alter.getVersion() + 1)
            alter.update("version")
            alter.setRef(alter.getRef() & "_ADAP_" & alter.getVersion().ToString)
            alter.insert()
            setInitInfo(alter, 0, mainForm.currentUser.getLogin(), Today, 0) ' version adaptée
            alter.updateAll()
            Dim newItemTabPage As New ObjectPresent(alter, "Adapter", True)
            newItemTabPage.loadTree()
            mainForm.addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        End If
    End Sub

    Private Sub searchingResultModifClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim alterRef As String = resultGrid.Rows(resultGrid.CurrentCell.RowIndex).Cells(0).Value
        If alterRef <> "" Then
            Dim alter As New Component
            alter = alter.getObjectByKey(alterRef, "Alternator", "alternator")
            Dim newItemTabPage As New ObjectPresent(alter, "Modifier")
            newItemTabPage.loadTree()
            mainForm.addTwoTabs(newItemTabPage.getleftTabPage(), newItemTabPage.getRightTabPage())
        End If
    End Sub

    Private Sub searchingResultDeleteClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim answer As MsgBoxResult = MsgBox("Do you really want to delete this alternator from DataBase ?", vbYesNo, "Delete Alternator")
        If answer = MsgBoxResult.Yes Then
            Dim alterRef As String = resultGrid.Rows(resultGrid.CurrentCell.RowIndex).Cells(0).Value
            If alterRef <> "" Then
                Dim alter As New Component
                alter = alter.getObjectByKey(alterRef, "Alternator", "alternator")
                If Not alter.delete() Then
                    MsgBox("Component cant be deleted", vbCritical)
                Else
                    resultGrid.Rows.RemoveAt(resultGrid.CurrentCell.RowIndex)
                End If
            End If
        End If
    End Sub

    Private Sub searchingResultCalculDebitClick(ByVal sender As Object, ByVal e As EventArgs)
        MsgBox("On va calculer le débit")
    End Sub

End Class

Public Class LoginForm
    Inherits Form
    Private WithEvents form As Form
    Private loginLabel As System.Windows.Forms.Label
    Private passwordLabel As System.Windows.Forms.Label
    Private loginTextBox As System.Windows.Forms.TextBox
    Private passwordTextBox As System.Windows.Forms.TextBox
    Private WithEvents button1 As System.Windows.Forms.Button
    Private WithEvents button2 As System.Windows.Forms.Button
    Private isConnected As Boolean = False
    Dim user As User

    Sub New()
        form = New Form()
        form.ShowInTaskbar = False
        form.Name = "loginForm"
        form.Text = "Login"
        form.Width = 250
        form.Height = 150
        form.StartPosition = FormStartPosition.CenterScreen
        form.Icon = My.Resources.ihmLogo

        loginLabel = New System.Windows.Forms.Label()
        loginLabel.Text = "login : "
        loginLabel.Location = New System.Drawing.Point(20, 20)

        loginTextBox = New System.Windows.Forms.TextBox()
        loginTextBox.Location = New System.Drawing.Point(20 + loginLabel.Width, 20)


        passwordLabel = New System.Windows.Forms.Label()
        passwordLabel.Text = "password : "
        passwordLabel.Location = New System.Drawing.Point(20, 50)

        passwordTextBox = New System.Windows.Forms.TextBox()
        passwordTextBox.Location = New System.Drawing.Point(20 + passwordLabel.Width, 50)
        passwordTextBox.PasswordChar = "*"


        button1 = New System.Windows.Forms.Button()
        button2 = New System.Windows.Forms.Button()
        button1.Text = "Cancel"
        button2.Text = "Login"

        button1.Location = New System.Drawing.Point(20, 80)
        button2.Location = New System.Drawing.Point(70 + button1.Width, 80)

        form.Controls.Add(loginLabel)
        form.Controls.Add(loginTextBox)
        form.Controls.Add(passwordLabel)
        form.Controls.Add(passwordTextBox)
        form.Controls.Add(button1)
        form.Controls.Add(button2)
        form.ShowDialog()
    End Sub

    Public Function getForm() As Control
        Return form
    End Function

    Private Function identifyUser(ByVal login As String, ByVal password As String) As Boolean
        Dim ok As Boolean = False
        Dim connectionString As String
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim sql As String
        Dim reader As SqlDataReader
        Dim source As String = System.Net.Dns.GetHostEntry("cre2-w01526").AddressList(0).ToString
        connectionString = "Data Source=" & source & ";Initial Catalog=AlternatorDatabase; Integrated Security=SSPI;"
        sql = "SELECT password, expired_days, created_date, user_right from [user] where login = '" & login & "'"
        connection = New SqlConnection(connectionString)
        Dim _password As String = ""
        Dim expiredDays As Integer
        Dim createdDate As Date
        Dim userRight As Integer
        Try
            connection.Open()
            command = New SqlCommand(sql, connection)
            reader = command.ExecuteReader()
            Try
                While reader.Read()
                    _password = reader(0)
                    expiredDays = reader(1)
                    createdDate = reader(2)
                    userRight = reader(3)
                End While
                If _password = password And (expiredDays - (Today - createdDate).TotalDays > 0 Or userRight = 1) Then
                    ok = True
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            Finally
                reader.Close()
            End Try
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        Return ok
    End Function

    Private Sub acceptButton_OnClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles button2.Click 'accept
        If loginTextBox.Text = "" Or passwordTextBox.Text = "" Then
            MsgBox("Login or Password is empty", vbCritical)
            Exit Sub
        End If

        If identifyUser(loginTextBox.Text, passwordTextBox.Text) Then
            isConnected = True
            user = New User(loginTextBox.Text)
            form.Dispose()
        Else
            MsgBox("Login failed or account expired !!", vbCritical)
        End If
    End Sub

    Private Sub cancelButton_OnClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click 'cancel
        form.Close()
    End Sub

    Public Function getConnected() As Boolean
        Return isConnected
    End Function

    Public Function getUser() As Object
        Return user
    End Function
End Class

Public Class CreateUserForm
    Private form As Form
    Private infoZone As System.Windows.Forms.GroupBox
    Private loginLabel As System.Windows.Forms.Label
    Private loginText As System.Windows.Forms.TextBox
    Private passwordLabel As System.Windows.Forms.Label
    Private passwordText As System.Windows.Forms.TextBox
    Private firstNameLabel As System.Windows.Forms.Label
    Private firstNameText As System.Windows.Forms.TextBox
    Private lastNameLabel As System.Windows.Forms.Label
    Private lastNameText As System.Windows.Forms.TextBox
    Private emailLabel As System.Windows.Forms.Label
    Private emailText As System.Windows.Forms.TextBox
    Private functionCompanyLabel As System.Windows.Forms.Label
    Private functionCompanyText As System.Windows.Forms.TextBox
    Private expiredLabel As System.Windows.Forms.Label
    Private expiredText As System.Windows.Forms.TextBox
    Private adminUserRight As RadioButton
    Private standardUserRight As RadioButton
    Private WithEvents cancelButton As System.Windows.Forms.Button
    Private WithEvents saveButton As System.Windows.Forms.Button
    Private isNewCreate As Boolean
    Sub New(Optional ByVal _isNewCreate As Boolean = vbTrue)
        isNewCreate = _isNewCreate
        form = New Form()
        form.ShowInTaskbar = False
        If isNewCreate Then
            form.Text = "Create a new user"
        Else
            form.Text = "Modify user's profile"
        End If
        form.StartPosition = FormStartPosition.CenterScreen
        form.Width = 300
        form.Height = 330

        infoZone = New System.Windows.Forms.GroupBox()
        infoZone.Text = "Enter these informations : "
        infoZone.AutoSize = True
        infoZone.Dock = DockStyle.Fill

        loginLabel = New System.Windows.Forms.Label
        loginLabel.Text = "Login : "
        loginLabel.Location = New System.Drawing.Point(20, 20)
        loginText = New System.Windows.Forms.TextBox()
        loginText.Width = 150
        loginText.Location = New System.Drawing.Point(25 + loginLabel.Width, 20)

        passwordLabel = New System.Windows.Forms.Label()
        passwordLabel.Text = "Password : "
        passwordLabel.Location = New System.Drawing.Point(20, 50)
        passwordText = New System.Windows.Forms.TextBox()
        passwordText.Width = 150
        passwordText.UseSystemPasswordChar = True
        passwordText.Location = New System.Drawing.Point(25 + passwordLabel.Width, 50)

        firstNameLabel = New System.Windows.Forms.Label()
        firstNameLabel.Text = "First Name : "
        firstNameLabel.Location = New System.Drawing.Point(20, 80)
        firstNameText = New System.Windows.Forms.TextBox()
        firstNameText.Width = 150
        firstNameText.Location = New System.Drawing.Point(25 + firstNameLabel.Width, 80)

        lastNameLabel = New System.Windows.Forms.Label()
        lastNameLabel.Text = "Last Name : "
        lastNameLabel.Location = New System.Drawing.Point(20, 110)
        lastNameText = New System.Windows.Forms.TextBox()
        lastNameText.Width = 150
        lastNameText.Location = New System.Drawing.Point(25 + lastNameLabel.Width, 110)

        emailLabel = New System.Windows.Forms.Label()
        emailLabel.Text = "Email : "
        emailLabel.Location = New System.Drawing.Point(20, 140)
        emailText = New System.Windows.Forms.TextBox()
        emailText.Width = 150
        emailText.Location = New System.Drawing.Point(25 + emailLabel.Width, 140)

        functionCompanyLabel = New System.Windows.Forms.Label()
        functionCompanyLabel.Text = "Function : "
        functionCompanyLabel.Location = New System.Drawing.Point(20, 170)
        functionCompanyText = New System.Windows.Forms.TextBox()
        functionCompanyText.Width = 150
        functionCompanyText.Location = New System.Drawing.Point(25 + functionCompanyLabel.Width, 170)

        expiredLabel = New System.Windows.Forms.Label
        expiredLabel.Text = "Expired day(s) : "
        expiredLabel.Location = New System.Drawing.Point(20, 200)
        expiredText = New System.Windows.Forms.TextBox
        expiredText.Width = 150
        expiredText.Location = New System.Drawing.Point(25 + expiredLabel.Width, 200)

        adminUserRight = New RadioButton()
        adminUserRight.Text = "admin user"
        adminUserRight.Checked = False
        adminUserRight.Location = New System.Drawing.Point(20, 230)
        AddHandler adminUserRight.Click, AddressOf adminUserRight_Click

        

        standardUserRight = New RadioButton()
        standardUserRight.Text = "normal user"
        standardUserRight.Checked = True
        standardUserRight.Location = New System.Drawing.Point(25 + adminUserRight.Width, 230)
        AddHandler standardUserRight.Click, AddressOf standardUserRight_Click

        cancelButton = New System.Windows.Forms.Button
        cancelButton.Text = "Cancel"
        cancelButton.TextAlign = ContentAlignment.MiddleCenter
        cancelButton.Location = New System.Drawing.Point(20, 260)
        saveButton = New System.Windows.Forms.Button
        saveButton.Text = "Save"
        saveButton.TextAlign = ContentAlignment.MiddleCenter
        saveButton.Location = New System.Drawing.Point(125 + cancelButton.Width, 260)


        form.Controls.Add(infoZone)
        infoZone.Controls.Add(loginLabel)
        infoZone.Controls.Add(loginText)
        infoZone.Controls.Add(passwordLabel)
        infoZone.Controls.Add(passwordText)
        infoZone.Controls.Add(firstNameLabel)
        infoZone.Controls.Add(firstNameText)
        infoZone.Controls.Add(lastNameLabel)
        infoZone.Controls.Add(lastNameText)
        infoZone.Controls.Add(emailLabel)
        infoZone.Controls.Add(emailText)
        infoZone.Controls.Add(functionCompanyLabel)
        infoZone.Controls.Add(functionCompanyText)
        infoZone.Controls.Add(adminUserRight)
        infoZone.Controls.Add(standardUserRight)
        infoZone.Controls.Add(cancelButton)
        infoZone.Controls.Add(saveButton)
        infoZone.Controls.Add(expiredLabel)
        infoZone.Controls.Add(expiredText)
    End Sub

    Public Function getForm() As Control
        Return form
    End Function

    Private Sub cancelButton_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles cancelButton.Click
        form.Close()
    End Sub

    Private Sub saveButton_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles saveButton.Click
        If loginText.Text = "" Then
            MsgBox("login is required", vbCritical)
            Exit Sub
        End If
        Dim user As User
        user = New User(loginText.Text)
        If user.getLogin() = loginText.Text And isNewCreate = True Then
            MsgBox("login is not available", vbCritical)
            Exit Sub
        ElseIf passwordText.Text = "" Then
            MsgBox("Password can be empty", vbCritical)
            Exit Sub
        Else
            user.setLogin(loginText.Text)
            user.setPassword(passwordText.Text)
            user.setFirstName(firstNameText.Text)
            user.setLastName(lastNameText.Text)
            user.setEmail(emailText.Text)
            user.setFunctionCompany(functionCompanyText.Text)
            If adminUserRight.Checked Then
                user.setUserRight(1)
            Else
                user.setUserRight(2)
            End If

            If isNewCreate Then
                user.setCreatedDate(Today)
                user.setExpiredDays(expiredText.Text)
                If user.create() Then
                    Dim answer As MsgBoxResult = MsgBox("User " & loginText.Text & " has been created")

                    'Dim msg As New System.Net.Mail.MailMessage("letuananha3@gmail.com", "tuan-anh.le@valeo.com", "Account created", "Your account has been created login : aaa, password : bbb")
                    'Dim client As New System.Net.Mail.SmtpClient("smtp.gmail.com", 587)
                    'client.EnableSsl = True
                    ''client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network
                    'client.Credentials = New System.Net.NetworkCredential("letuananha3@gmail.com", "RJOntp97")
                    'Try
                    '    client.Send(msg)
                    'Catch ex As Exception
                    '    MsgBox(ex.Message)
                    'End Try
                    If answer = MsgBoxResult.Ok Then
                        form.Close()
                    End If
                End If
            Else ' c'est un mise à jour
                If user.save() Then
                    Dim answer As MsgBoxResult = MsgBox("User " & loginText.Text & " has been Modified")
                    If answer = MsgBoxResult.Ok Then
                        form.Close()
                    End If
                End If
            End If
        End If
    End Sub

    Public Sub loadFormFromUserProfile(ByVal user As User)
        loginText.Text = user.getLogin()
        loginText.Enabled = False
        firstNameText.Text = user.getFirstName()
        lastNameText.Text = user.getLastName()
        emailText.Text = user.getEmail()
        functionCompanyText.Text = user.getFunctionCompany()
        If user.getUserRight() = 1 Then
            adminUserRight.Checked = True
        Else
            standardUserRight.Checked = True
        End If
        adminUserRight.Enabled = False
        standardUserRight.Enabled = False
        expiredText.Text = user.getExpiredDays
        expiredText.Enabled = False
    End Sub

    Private Sub adminUserRight_Click(ByVal sender As Object, ByVal e As EventArgs)
        expiredText.Text = -1
        expiredText.Enabled = False
    End Sub

    Private Sub standardUserRight_Click(ByVal sender As Object, ByVal e As EventArgs)
        expiredText.Text = 0
        expiredText.Enabled = True
    End Sub

End Class

Public Class DeleteUserForm
    Inherits mainForm
    Private form As Form
    Private listLogins As ComboBox
    Private WithEvents deleteButton As System.Windows.Forms.Button
    Sub New()
        form = New Form()
        form.ShowInTaskbar = False
        form.StartPosition = FormStartPosition.CenterParent
        form.Width = 250
        form.Height = 100
        form.Text = "Delete a user"

        listLogins = loadItemsToComboBox("[user]", "login", " WHERE user_right = 2", "login", "login")
        listLogins.Location = New System.Drawing.Point(20, 20)

        deleteButton = New System.Windows.Forms.Button
        deleteButton.Text = "Delete"
        deleteButton.TextAlign = ContentAlignment.MiddleCenter
        deleteButton.Location = New System.Drawing.Point(25 + listLogins.Width, 20)

        form.Controls.Add(listLogins)
        form.Controls.Add(deleteButton)
    End Sub

    Public Function getForm() As Control
        Return form
    End Function

    Private Sub deleteButton_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles deleteButton.Click
        Dim user As User
        user = New User(listLogins.Text)
        If user.delete() Then
            Dim answer As MsgBoxResult = MsgBox("Delete success !!")
            If answer = MsgBoxResult.Ok Then
                form.Close()
            End If
        Else
            MsgBox("User can be deleted", vbCritical)
        End If
    End Sub
End Class

Public Class adapterForm
    Inherits mainForm
    Private form As Form
    Private groupBox As New System.Windows.Forms.GroupBox
    Private WithEvents componentList As New ComboBox
    Private WithEvents referenceList As New ComboBox
    Private WithEvents overWriteButton As System.Windows.Forms.Button
    Private WithEvents adapterButton As System.Windows.Forms.Button
    Private componentName As String
    Private componentRef As String
    Private overWrite As Boolean
    Private user As User

    Sub New(ByVal user As User)
        Me.user = user
        form = New Form()
        form.ShowInTaskbar = False
        form.Text = "Adapter a component"
        form.StartPosition = FormStartPosition.CenterScreen
        form.Width = 300
        form.Height = 150

        groupBox.Text = "Choose a component to adapter : "
        groupBox.AutoSize = True
        groupBox.Dock = DockStyle.Fill

        Dim l1 As New System.Windows.Forms.Label
        l1.Text = "Component : "
        l1.Location = New System.Drawing.Point(20, 20)

        componentList.Location = New System.Drawing.Point(25 + l1.Width, 20)
        Dim listValues As String() = New String() {"alternator", "stator", "rotor", "rectifier", "stator_coil", "stator_core", "slot_definition", "claw_poles", "field_core", "field_coil", "material_magnetic", "material_conductor", "thermal_coefficient"}
        componentList.DataSource = listValues
        Dim l2 As New System.Windows.Forms.Label
        l2.Text = "Reference : "
        l2.Location = New System.Drawing.Point(20, 50)
        Dim obj As New Component
        Dim condition As String = ""
        If user.getUserRight() > 1 Then
            condition = "WHERE editor = '" & user.getLogin() & "' OR is_original = 1"
        End If
        referenceList = loadItemsToComboBox("alternator", "ref", condition, "ref", "ref")
        referenceList.Location = New System.Drawing.Point(25 + l2.Width, 50)

        overWriteButton = New System.Windows.Forms.Button
        overWriteButton.Text = "Modify"
        overWriteButton.TextAlign = ContentAlignment.MiddleCenter
        overWriteButton.Location = New System.Drawing.Point(130, 90)
        If user.getUserRight() > 1 Then
            overWriteButton.Enabled = False
        End If
        adapterButton = New System.Windows.Forms.Button
        adapterButton.Text = "Adapter"
        adapterButton.TextAlign = ContentAlignment.MiddleCenter
        adapterButton.Location = New System.Drawing.Point(130 + overWriteButton.Width, 90)

        form.Controls.Add(groupBox)
        groupBox.Controls.Add(l1)
        groupBox.Controls.Add(l2)
        groupBox.Controls.Add(componentList)
        groupBox.Controls.Add(referenceList)
        groupBox.Controls.Add(overWriteButton)
        groupBox.Controls.Add(adapterButton)
    End Sub

    Private Sub componentList_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles componentList.SelectedValueChanged
        Dim condition As String = ""
        If user.getUserRight() > 1 Then
            condition = "WHERE editor = '" & user.getLogin() & "' OR is_original = 1"
        End If
        referenceList.DataSource = loadItemsToComboBox(componentList.Text, "ref", condition, "ref", "ref").DataSource
    End Sub

    Private Sub referenceList_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles referenceList.SelectedValueChanged
        Dim obj As New Component
        obj = obj.getObjectByKey(referenceList.Text, columnNameToFunctionName(componentList.Text), componentList.Text)
        If obj.getIsOriginal() = 1 Then
            If user.getUserRight() > 1 Then
                overWriteButton.Enabled = False
            Else
                overWriteButton.Enabled = True
                adapterButton.Enabled = True
            End If
        Else
            adapterButton.Enabled = False
            overWriteButton.Enabled = True
        End If
    End Sub

    Function getForm() As System.Windows.Forms.Form
        Return form
    End Function

    Private Sub overWriteButton_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles overWriteButton.Click
        componentName = componentList.Text
        componentRef = referenceList.Text
        overWrite = True
        form.Dispose()
    End Sub

    Private Sub adapter_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles adapterButton.Click
        componentName = componentList.Text
        componentRef = referenceList.Text
        overWrite = False
        form.Dispose()
    End Sub

    Function getComponentRef() As String
        Return componentRef
    End Function

    Function getComponentName() As String
        Return componentName
    End Function

    Function isOverWrite() As Boolean
        Return overWrite
    End Function

End Class

Public Class DeleteComponentForm
    Inherits mainForm
    Private WithEvents form As Form
    Private groupBox As New System.Windows.Forms.GroupBox
    Private WithEvents componentList As New ComboBox
    Private WithEvents referenceList As New ComboBox
    Private WithEvents deleteButton As System.Windows.Forms.Button
    Private componentName As String
    Private componentRef As String

    Sub New()
        form = New Form()
        form.ShowInTaskbar = False
        form.Text = "Delete a component"
        form.StartPosition = FormStartPosition.CenterScreen
        form.Width = 300
        form.Height = 150

        groupBox.Text = "Choose a reference to delete : "
        groupBox.AutoSize = True
        groupBox.Dock = DockStyle.Fill

        Dim l1 As New System.Windows.Forms.Label
        l1.Text = "Component : "
        l1.Location = New System.Drawing.Point(20, 20)

        componentList.Location = New System.Drawing.Point(25 + l1.Width, 20)
        'Dim listDisplay As String(1 To 20, 1 To 20) 
        '= New String() {"alternator", "stator", "rotor", "rectifier"}


        getAllTablesList(componentList)
        Dim l2 As New System.Windows.Forms.Label
        l2.Text = "Reference : "
        l2.Location = New System.Drawing.Point(20, 50)
        Dim obj As New Component
        Dim condition As String = ""
        If mainForm.currentUser.getUserRight() > 1 Then
            condition = "WHERE editor = '" & mainForm.currentUser.getLogin() & "'"
        End If
        If componentList.Text = "" Then
            referenceList.Enabled = False
        Else
            referenceList = loadItemsToComboBox(componentList.Text, "ref", condition, "ref", "ref")
        End If
        referenceList.Location = New System.Drawing.Point(25 + l2.Width, 50)

        deleteButton = New System.Windows.Forms.Button
        deleteButton.Text = "Delete"
        deleteButton.TextAlign = ContentAlignment.MiddleCenter
        deleteButton.Location = New System.Drawing.Point(200, 80)
        deleteButton.Width = 50

        form.Controls.Add(groupBox)
        groupBox.Controls.Add(l1)
        groupBox.Controls.Add(l2)
        groupBox.Controls.Add(componentList)
        groupBox.Controls.Add(referenceList)
        groupBox.Controls.Add(deleteButton)
    End Sub

    Private Sub getAllTablesList(ByRef cbb)
        cbb.Items.Add(New Item("alternator", "alternator"))
        cbb.Items.Add(New Item("rotor", "rotor"))
        cbb.Items.Add(New Item("stator", "stator"))
        cbb.Items.Add(New Item("rectifier", "rectifier"))
        cbb.Items.Add(New Item("slot definition", "slot_definition"))
        cbb.Items.Add(New Item("stator core", "stator_core"))
        cbb.Items.Add(New Item("stator coil", "stator_coil"))
    End Sub

    Public Function getForm() As Control
        Return form
    End Function

    Private Sub componentList_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles componentList.SelectedIndexChanged
        Dim condition As String = ""
        If mainForm.currentUser.getUserRight() > 1 Then
            condition = "WHERE editor = '" & mainForm.currentUser.getLogin() & "'"
        End If
        groupBox.Controls.Remove(referenceList)
        referenceList = loadItemsToComboBox(componentList.SelectedItem.value, "ref", condition, "ref", "ref")
        referenceList.Location = New System.Drawing.Point(componentList.Left, 50)
        groupBox.Controls.Add(referenceList)
    End Sub

    Private Sub deleteButton_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles deleteButton.Click
        Dim obj As New Component
        obj = obj.getObjectByKey(referenceList.Text, columnNameToFunctionName(componentList.Text), componentList.SelectedItem.Value)
        If Not obj.getRef() Is Nothing Then
            If Not obj.delete() Then
                MsgBox("Component cant be deleted", vbCritical)
            Else
                Me.form.Dispose()
            End If
        Else
            MsgBox("Component couldn't be found", vbCritical)
        End If
    End Sub
End Class

Public Class Item
    Public name As String
    Public value As String

    Sub New(ByVal name As String, ByVal value As String)
        Me.name = name
        Me.value = value
    End Sub

    Public Overrides Function ToString() As String
        Return name
    End Function

End Class

Public Class ImportDataForm
    Inherits mainForm
    Private WithEvents openFile As OpenFileDialog

    Sub New()
        openFile = New OpenFileDialog
        openFile.Filter = "Fichier excel(*.xls)|*.xls"
        openFile.ShowDialog()
    End Sub

    Public Function getFileName() As String
        Return openFile.FileName
    End Function

End Class

Public Class ExportDataForm
    Inherits mainForm
    Private form As System.Windows.Forms.Form
    Private comboBox As System.Windows.Forms.ComboBox
    Private WithEvents exportButton As System.Windows.Forms.Button
    Private saveFile As System.Windows.Forms.SaveFileDialog

    Sub New()
        form = New System.Windows.Forms.Form
        form.Text = "Export Data"
        form.StartPosition = FormStartPosition.CenterScreen
        form.Width = 250
        form.Height = 100

        comboBox = New System.Windows.Forms.ComboBox
        Dim condition As String = ""
        If mainForm.currentUser.getUserRight() > 1 Then
            condition = "WHERE editor = '" & mainForm.currentUser.getLogin() & "'"
        End If
        comboBox = loadItemsToComboBox("Alternator", "ref", condition, "ref", "ref")
        comboBox.Location = New System.Drawing.Point(20, 20)

        exportButton = New System.Windows.Forms.Button
        exportButton.Text = "Export"
        exportButton.TextAlign = ContentAlignment.MiddleCenter
        exportButton.Location = New System.Drawing.Point(25 + comboBox.Width, 20)

        form.Controls.Add(comboBox)
        form.Controls.Add(exportButton)
    End Sub

    Public Function getForm() As Control
        Return form
    End Function

    Public Sub exportButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exportButton.Click
        Dim ref As String = comboBox.Text
        Dim obj As New Alternator
        If obj.exist("alternator", ref) Then
            saveFile = New System.Windows.Forms.SaveFileDialog

            saveFile.Filter = "Excel Files(*.xls)|*.xls"
            saveFile.OverwritePrompt = False
            saveFile.ShowDialog()
            If saveFile.FileName <> "" Then
                form.Dispose()
                writeObjectToFile(ref, saveFile.FileName)
            End If
        Else
            MsgBox("Alternator cant be found in the data base", vbCritical)
        End If
    End Sub

    Private Sub writeObjectToFile(ByVal ref As String, ByVal fileName As String)
        Dim defaultForm As String = "e:\documents and settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\export\form.xls"
        Dim excelApp As Excel.Application
        Dim excelBook As Workbook
        Dim excelWorkSheet As Worksheet
        excelApp = New Excel.Application
        excelBook = excelApp.Workbooks.Open(defaultForm)
        excelWorkSheet = excelBook.Worksheets("sheet1")

        Dim alter As New Alternator
        alter = alter.getObjectByKey(ref, "Alternator", "alternator")
        Dim row As Integer = 10
        Dim col As Integer = 4
        ' Exporte les infos généreaux
        exportAlter(row, col, 5, alter, excelWorkSheet)

        row += 1 ' 1 ligne blance
        ' export stator
        Dim stator As New Stator
        stator = stator.getObjectByKey(alter.getStator(), "Stator", "stator")
        row += 1 ' writing stator's ref
        excelWorkSheet.Cells(row, col) = stator.getRef()

        '' export stator core
        row += 1 ' 1 lienge blance
        Dim statorCore As New StatorCore
        statorCore = statorCore.getObjectByKey(stator.getStatorCore(), "StatorCore", "stator_core")
        exportAlter(row, col, 5, statorCore, excelWorkSheet)

        row += 1 ' ligne blance
        Dim materialMagneticStator As New MaterialMagnetic
        materialMagneticStator = materialMagneticStator.getObjectByKey(statorCore.getMaterialMagnetic(), "MaterialMagnetic", "material_magnetic")
        row += 1
        exportAlter(row, col, 9, materialMagneticStator, excelWorkSheet)

        row += 1 ' 1 ligne blace
        Dim slotDefinition As New SlotDefinition
        slotDefinition = slotDefinition.getObjectByKey(stator.getSlotDefinition(), "SlotDefinition", "slot_definition")
        row += 1
        exportAlter(row, col, 10, slotDefinition, excelWorkSheet)

        row += 1
        ' 1 ligne blace
        Dim statorCoil As New StatorCoil
        statorCoil = statorCoil.getObjectByKey(stator.getStatorCoil(), "StatorCoil", "stator_coil")
        row += 1
        exportAlter(row, col, 20, statorCoil, excelWorkSheet)

        row += 1 ' ligne blance
        Dim materialConductorStator As New MaterialConductor
        materialConductorStator = materialConductorStator.getObjectByKey(statorCoil.getMaterialConductor(), "MaterialConductor", "material_conductor")
        row += 1
        exportAlter(row, col, 4, materialConductorStator, excelWorkSheet)

        row += 1 ' 1 ligne blance
        ' export rotor
        Dim rotor As New Rotor
        rotor = rotor.getObjectByKey(alter.getRotor(), "Rotor", "rotor")
        row += 1
        excelWorkSheet.Cells(row, col) = rotor.getRef()
        exportAlter(row, col, 1, rotor, excelWorkSheet)

        row += 1 ' 1 ligne blance
        Dim clawPoles As New ClawPoles
        clawPoles = clawPoles.getObjectByKey(rotor.getClawPoles(), "ClawPoles", "claw_poles")
        row += 1
        exportAlter(row, col, 23, clawPoles, excelWorkSheet)

        row += 1 ' ligne blance
        Dim materialMagneticClawPoles As New MaterialMagnetic
        materialMagneticClawPoles = materialMagneticClawPoles.getObjectByKey(clawPoles.getMaterialMagnetic(), "MaterialMagnetic", "material_magnetic")
        row += 1
        exportAlter(row, col, 9, materialMagneticClawPoles, excelWorkSheet)

        row += 1 ' 1 ligne blance
        Dim fieldCore As New FieldCore
        fieldCore = fieldCore.getObjectByKey(rotor.getFieldCore(), "FieldCore", "field_core")
        row += 1
        exportAlter(row, col, 7, fieldCore, excelWorkSheet)

        row += 1 ' ligne blance
        Dim materialMagneticFieldCore As New MaterialMagnetic
        materialMagneticFieldCore = materialMagneticFieldCore.getObjectByKey(fieldCore.getMaterialMagnetic(), "MaterialMagnetic", "material_magnetic")
        row += 1
        exportAlter(row, col, 9, materialMagneticFieldCore, excelWorkSheet)

        row += 1 ' 1 ligne blance
        Dim fieldCoil As New FieldCoil
        fieldCoil = fieldCoil.getObjectByKey(rotor.getFieldCoil(), "FieldCoil", "field_coil")
        row += 1
        exportAlter(row, col, 14, fieldCoil, excelWorkSheet)

        row += 1 ' ligne blance
        Dim materialConductorRotor As New MaterialConductor
        materialConductorRotor = materialConductorRotor.getObjectByKey(fieldCoil.getMaterialConductor(), "MaterialConductor", "material_conductor")
        row += 1
        exportAlter(row, col, 4, materialConductorRotor, excelWorkSheet)

        Try
            excelBook.SaveAs(fileName)
            excelBook.Close()
            excelApp.Quit()
            MsgBox("Export data success !!!")
            mainForm.Activate()
        Catch e As Exception
            excelBook.Close(False)
            excelApp.Quit()
            MsgBox("File not saved", vbCritical)
            mainForm.Activate()
            Exit Sub
        End Try
    End Sub

    Private Sub exportAlter(ByRef row As Integer, ByVal col As Integer, ByVal nberLignes As Integer, ByVal obj As Component, ByRef workSheet As Worksheet)
        For i As Integer = 1 To nberLignes Step 1
            row += 1
            Dim name As String = workSheet.Cells(row, col - 1).value
            Dim value As Object = obj.getAttribute(columnNameToFunctionName(name))
            If Not value Is Nothing Then
                workSheet.Cells(row, col) = value
            End If
        Next
    End Sub
End Class

Public Class CalculForm
    Inherits mainForm
    Private WithEvents parameterPage As TabPage
    Private WithEvents resultPage As TabPage
    Private contextTab As System.Windows.Forms.TabControl
    Dim combo As System.Windows.Forms.ComboBox
    Dim label2 As New System.Windows.Forms.GroupBox
    Dim PC_check As New System.Windows.Forms.RadioButton
    Dim CP_check As New System.Windows.Forms.RadioButton
    Dim I_CP As New System.Windows.Forms.TextBox
    Dim I_CPLabel As New System.Windows.Forms.Label
    Dim environmentZone As New System.Windows.Forms.GroupBox
    Dim coldCheck As New System.Windows.Forms.RadioButton
    Dim hotCheck As New System.Windows.Forms.RadioButton
    Dim addButton As New System.Windows.Forms.PictureBox
    Dim removeButton As New System.Windows.Forms.PictureBox
    Dim testCasesLabel As New System.Windows.Forms.Label
    Dim testCasesTab As System.Windows.Forms.TabControl
    Dim generalPage As New TabPage
    Dim objectivesPage As New TabPage
    Dim speedsPage As New TabPage
    Dim checkListBox As New System.Windows.Forms.CheckedListBox
    Dim speedsGrid As New System.Windows.Forms.DataGridView
    Dim preHeatingText As New System.Windows.Forms.TextBox
    Dim defaultSpeeds As New System.Windows.Forms.CheckBox
    Dim executeButton As New System.Windows.Forms.Button
    Dim resultsTab As New System.Windows.Forms.TabControl
    Dim tablePage As New System.Windows.Forms.TabPage
    Dim graphPage As New System.Windows.Forms.TabPage
    Dim VDACalculePage As New System.Windows.Forms.TabPage
    Dim GMNACalculePage As New System.Windows.Forms.TabPage
    Dim VDAGrid As New System.Windows.Forms.DataGridView
    Dim GMNAGrid As New System.Windows.Forms.DataGridView
    Dim torqueMapButton As New System.Windows.Forms.Button
    Dim exportButton As New System.Windows.Forms.Button
    Dim closeButton As New System.Windows.Forms.Button
    Dim torqueMapPage As New System.Windows.Forms.TabPage
    Dim torqueTab As New System.Windows.Forms.TabControl
    Sub New()
        parameterPage = New System.Windows.Forms.TabPage
        parameterPage.Text = "Calculate Flux"
        resultPage = New System.Windows.Forms.TabPage
        resultPage.Text = "Results"
        ' context tab
        addContextTabs()
        AddHandler parameterPage.SizeChanged, AddressOf parameterPage_OnSizeChanged
        AddHandler resultPage.SizeChanged, AddressOf resultPage_OnSizeChanged

        ' calculate button
        Dim toolTip1 As New System.Windows.Forms.ToolTip
        toolTip1.ShowAlways = True
        executeButton.Image = WindowsApplication1.My.Resources.calculate
        executeButton.Width = 50
        executeButton.Height = 50
        executeButton.BackgroundImageLayout = ImageLayout.Stretch
        toolTip1.SetToolTip(executeButton, "Calculte flux")
        parameterPage.Controls.Add(executeButton)
        AddHandler executeButton.Click, AddressOf executeButton_OnClick

        ' Torque and Eff Map Button
        torqueMapButton.Image = WindowsApplication1.My.Resources.torquemap
        torqueMapButton.Size = New System.Drawing.Size(50, 50)
        torqueMapButton.BackgroundImageLayout = ImageLayout.Stretch
        toolTip1.SetToolTip(torqueMapButton, "Torque and Efficiency Map")
        parameterPage.Controls.Add(torqueMapButton)
        AddHandler torqueMapButton.Click, AddressOf torqueMapButton_OnClick

        ' Export to excel Button
        exportButton.Image = WindowsApplication1.My.Resources.export
        exportButton.Size = New System.Drawing.Size(50, 50)
        exportButton.BackgroundImageLayout = ImageLayout.Stretch
        toolTip1.SetToolTip(exportButton, "Export to Excel")
        exportButton.Enabled = False
        parameterPage.Controls.Add(exportButton)
        AddHandler exportButton.Click, AddressOf exportButton_OnClick

        ' Close Calcule window
        closeButton.Image = WindowsApplication1.My.Resources.close
        closeButton.Size = New System.Drawing.Size(50, 50)
        closeButton.BackgroundImageLayout = ImageLayout.Stretch
        toolTip1.SetToolTip(closeButton, "Close")
        parameterPage.Controls.Add(closeButton)
        AddHandler closeButton.Click, AddressOf closeButton_OnClick
    End Sub

    Private Sub addContextTabs()
        contextTab = New System.Windows.Forms.TabControl
        contextTab.Height = leftTabControl.Height / 5 * 2
        
        generalPage.Text = "Context"
        objectivesPage.Text = "Objectives"
        speedsPage.Text = "Speeds"
        contextTab.TabPages.Add(generalPage)
        contextTab.TabPages.Add(objectivesPage)
        contextTab.TabPages.Add(speedsPage)
        parameterPage.Controls.Add(contextTab)
        createGeneralPage(generalPage)
        createObjectivesPage(objectivesPage)
        createSpeedsPage(speedsPage)
    End Sub

    
    Public Function getLeftTabPage() As Control
        Return parameterPage
    End Function

    Public Function getRightTabPage() As Control
        Return resultPage
    End Function

    Private Sub parameterPage_OnSizeChanged(ByVal sender As Object, ByVal e As EventArgs)
        contextTab.Width = parameterPage.Width
        executeButton.Location = New System.Drawing.Point(20, parameterPage.Height - 70)
        torqueMapButton.Location = New System.Drawing.Point(10 + executeButton.Right, parameterPage.Height - 70)
        exportButton.Location = New System.Drawing.Point(10 + torqueMapButton.Right, parameterPage.Height - 70)
        closeButton.Location = New System.Drawing.Point(10 + exportButton.Right, parameterPage.Height - 70)
    End Sub

    Private Sub createGeneralPage(ByRef generalPage As TabPage)
        Dim label1 As New System.Windows.Forms.Label
        label1.Text = "Alternator : "
        label1.Location = New System.Drawing.Point(20, 20)
        combo = loadItemsToComboBox("alternator", "ref", " WHERE is_original = 1 OR editor = '" & mainForm.currentUser.getLogin() & "'", "ref", "ref")
        combo.Name = "alternator"
        combo.Location = New System.Drawing.Point(label1.Right, 20)
        AddHandler combo.Leave, AddressOf combo_OnLeave

        label2.Text = "Test Conditions : "
        label2.Location = New System.Drawing.Point(20, label1.Location.Y + label1.Height + 5)
        label2.Width = 220
        label2.Height = 50

        PC_check.Text = "PC"
        PC_check.Width = 50
        PC_check.Location = New System.Drawing.Point(20, 20)
        PC_check.Checked = True

        CP_check.Text = "CP"
        CP_check.Location = New System.Drawing.Point(50 + PC_check.Width, 20)
        CP_check.Width = 50
        AddHandler CP_check.CheckedChanged, AddressOf CP_check_OnChecked

        I_CPLabel.Text = "I_CP : "
        I_CPLabel.Location = New System.Drawing.Point(20, PC_check.Location.Y + PC_check.Height + 5)
        I_CPLabel.Width = 40
        I_CP.Location = New System.Drawing.Point(20 + I_CPLabel.Width, I_CPLabel.Location.Y)
        I_CP.Visible = False
        I_CPLabel.Visible = False
        AddHandler I_CP.Leave, AddressOf I_CP_OnLeave

        environmentZone.Text = "Test environment : "
        environmentZone.Width = 220
        environmentZone.Height = 50
        environmentZone.Location = New System.Drawing.Point(20, label2.Bottom)
        AddHandler label2.SizeChanged, AddressOf label2_OnSizeChanged
        coldCheck.Text = "Cold"
        coldCheck.Width = 50
        coldCheck.Location = New System.Drawing.Point(20, 20)
        coldCheck.Checked = True
        hotCheck.Text = "Hot"
        hotCheck.Width = 50
        hotCheck.Location = New System.Drawing.Point(50 + coldCheck.Width, 20)
        environmentZone.Controls.Add(coldCheck)
        environmentZone.Controls.Add(hotCheck)
        AddHandler environmentZone.LocationChanged, AddressOf environmentZone_OnLocationChanged

        addButton.Image = WindowsApplication1.My.Resources.add
        addButton.Location = New System.Drawing.Point(20, environmentZone.Bottom + 10)
        addButton.Width = 32
        addButton.Height = 32
        removeButton.Image = WindowsApplication1.My.Resources.remove
        removeButton.Location = New System.Drawing.Point(addButton.Right, environmentZone.Bottom + 10)
        removeButton.Width = 32
        removeButton.Height = 32
        AddHandler addButton.MouseEnter, AddressOf addButton_OnMouseEnter
        AddHandler removeButton.MouseEnter, AddressOf removeButton_OnMouseEnter
        AddHandler addButton.MouseClick, AddressOf addButton_OnMouseClick
        AddHandler removeButton.MouseClick, AddressOf removeButton_OnMouseClick

        testCasesLabel.Text = "test case"
        testCasesLabel.Location = New System.Drawing.Point(removeButton.Right + 10, environmentZone.Bottom + 20)
        generalPage.Controls.Add(label1)
        generalPage.Controls.Add(combo)
        generalPage.Controls.Add(label2)
        generalPage.Controls.Add(environmentZone)
        generalPage.Controls.Add(addButton)
        generalPage.Controls.Add(removeButton)
        generalPage.Controls.Add(testCasesLabel)
        label2.Controls.Add(PC_check)
        label2.Controls.Add(CP_check)
        label2.Controls.Add(I_CPLabel)
        label2.Controls.Add(I_CP)
    End Sub

    Private Sub combo_OnLeave(ByVal sender As Object, ByVal e As EventArgs)
        Dim obj As New Component
        If Not obj.exist("alternator", combo.Text) Then
            Dim msgAnswer As MsgBoxResult = MsgBox("Alternator doesn't exist in data base", vbCritical)
            combo.Focus()
        End If

    End Sub

    Private Sub CP_check_OnChecked(ByVal sender As Object, ByVal e As EventArgs)
        If CP_check.Checked = True Then
            label2.Height = 80
            I_CP.Visible = True
            I_CPLabel.Visible = True
        Else
            label2.Height = 50
            I_CP.Visible = False
            I_CPLabel.Visible = False
        End If
    End Sub

    Private Sub label2_OnSizeChanged(ByVal sender As Object, ByVal e As EventArgs)
        environmentZone.Location = New System.Drawing.Point(20, label2.Bottom)
    End Sub

    Private Sub addButton_OnMouseEnter(ByVal sender As Object, ByVal e As EventArgs)
        addButton.Cursor = Cursors.Hand
    End Sub

    Private Sub removeButton_OnMouseEnter(ByVal sender As Object, ByVal e As EventArgs)
        removeButton.Cursor = Cursors.Hand
    End Sub

    Private Sub addButton_OnMouseClick(ByVal sender As Object, ByVal e As MouseEventArgs)
        If testCasesTab Is Nothing Then
            testCasesTab = New System.Windows.Forms.TabControl
            testCasesTab.Width = contextTab.Width - 30
            testCasesTab.Height = 100
            testCasesTab.Location = New System.Drawing.Point(20, addButton.Bottom + 10)
            contextTab.Height += 100
            generalPage.Controls.Add(testCasesTab)
            Dim tab As New TestCase(1)
            testCasesTab.Controls.Add(tab.getTabPage)
        Else
            Dim tab As New TestCase(testCasesTab.TabPages.Count + 1)
            testCasesTab.Controls.Add(tab.getTabPage)
            testCasesTab.SelectedTab = tab.getTabPage
        End If
    End Sub

    Private Sub environmentZone_OnLocationChanged(ByVal sender As Object, ByVal e As EventArgs)
        addButton.Location = New System.Drawing.Point(20, environmentZone.Bottom + 10)
        removeButton.Location = New System.Drawing.Point(addButton.Right, environmentZone.Bottom + 10)
        testCasesLabel.Location = New System.Drawing.Point(removeButton.Right + 10, environmentZone.Bottom + 20)
        If Not testCasesTab Is Nothing Then
            testCasesTab.Location = New System.Drawing.Point(20, addButton.Bottom + 10)
        End If
    End Sub

    Private Class TestCase
        Private tabPage As System.Windows.Forms.TabPage
        Private temperatureLabel As System.Windows.Forms.Label
        Private temperatureText As System.Windows.Forms.TextBox
        Private VdcLabel As System.Windows.Forms.Label
        Private VdcText As System.Windows.Forms.TextBox
        Sub New(ByVal number As Integer)
            tabPage = New System.Windows.Forms.TabPage
            tabPage.Text = "Case " & number
            temperatureLabel = New System.Windows.Forms.Label
            temperatureLabel.Text = "Ambient Temperature : "
            temperatureLabel.Width = 120
            temperatureLabel.Location = New System.Drawing.Point(10, 20)
            temperatureText = New System.Windows.Forms.TextBox
            temperatureText.Name = "temperatureText"
            temperatureText.Location = New System.Drawing.Point(15 + temperatureLabel.Width, 20)
            AddHandler temperatureText.Leave, AddressOf temperatureText_OnLeave

            VdcLabel = New System.Windows.Forms.Label
            VdcLabel.Text = "Vdc : "
            VdcLabel.Location = New System.Drawing.Point(10, temperatureLabel.Bottom)
            VdcText = New System.Windows.Forms.TextBox
            VdcText.Name = "VdcText"
            VdcText.Location = New System.Drawing.Point(temperatureText.Location.X, VdcLabel.Location.Y)
            AddHandler VdcText.Leave, AddressOf VdcText_OnLeave


            tabPage.Controls.Add(temperatureLabel)
            tabPage.Controls.Add(temperatureText)
            tabPage.Controls.Add(VdcLabel)
            tabPage.Controls.Add(VdcText)
        End Sub
        Function getTabPage() As Control
            Return Me.tabPage
        End Function

        Private Sub temperatureText_OnLeave(ByVal sender As Object, ByVal e As EventArgs)
            If Not IsNumeric(temperatureText.Text) Then
                MsgBox("Temperature must have a numeric value", vbCritical)
                temperatureText.Focus()
            End If
        End Sub

        Private Sub VdcText_OnLeave(ByVal sender As Object, ByVal e As EventArgs)
            If Not IsNumeric(VdcText.Text) Then
                VdcText.Focus()
                MsgBox("Vdc must have a numeric value", vbCritical)
            End If
        End Sub

    End Class

    Private Sub removeButton_OnMouseClick(ByVal sender As Object, ByVal e As MouseEventArgs)
        If Not testCasesTab Is Nothing Then
            If testCasesTab.TabPages.Count > 1 Then
                testCasesTab.TabPages.RemoveAt(testCasesTab.TabPages.Count - 1)
            End If
        End If
    End Sub

    Private Sub createObjectivesPage(ByRef objectivesPage As TabPage)
        checkListBox.Items.Add("Output Current")
        checkListBox.Items.Add("Torque")
        checkListBox.Items.Add("I exc")
        checkListBox.Items.Add("Efficiency")
        checkListBox.Items.Add("T Stator")
        checkListBox.Items.Add("T Rotor")
        checkListBox.Items.Add("Bearing")
        checkListBox.Items.Add("Fan losses")
        checkListBox.Items.Add("Diode")
        checkListBox.Items.Add("Stator joule")
        checkListBox.Items.Add("Total")
        checkListBox.Items.Add("RC")
        checkListBox.Items.Add("Mech")
        checkListBox.SetItemChecked(0, True)
        checkListBox.SetItemChecked(1, True)
        checkListBox.SetItemChecked(3, True)
        checkListBox.Width = contextTab.Width
        checkListBox.Height = contextTab.Height
        objectivesPage.Controls.Add(checkListBox)
    End Sub

    Private Sub createSpeedsPage(ByVal speedsPage As TabPage)
        Dim preHeatingLabel As New System.Windows.Forms.Label
        preHeatingLabel.Text = "Pre-Heating speed : "
        preHeatingLabel.Width = 150
        preHeatingLabel.Location = New System.Drawing.Point(20, 20)
        preHeatingText.Location = New System.Drawing.Point(20 + preHeatingLabel.Width, 20)

        defaultSpeeds.Text = "Default Speeds"
        defaultSpeeds.Location = New System.Drawing.Point(20, 20 + preHeatingLabel.Height)
        

        speedsGrid.ColumnCount = 2
        speedsGrid.RowCount = 11
        speedsGrid.Location = New System.Drawing.Point(20, defaultSpeeds.Bottom)
        speedsGrid.Width = 200
        speedsGrid.Height = 150
        speedsGrid.RowHeadersVisible = False
        speedsGrid.AllowUserToAddRows = True
        speedsGrid.AllowUserToDeleteRows = False
        speedsGrid.AllowUserToOrderColumns = False
        speedsGrid.AllowUserToResizeColumns = False
        speedsGrid.AllowUserToResizeRows = False
        speedsGrid.Columns(0).HeaderText = "N°"
        speedsGrid.Columns(1).HeaderText = "Speed"
        For i As Integer = 0 To 9
            speedsGrid.Rows(i).Cells(0).Value = i + 1
        Next
        speedsGrid.Columns(0).ReadOnly = True
        speedsGrid.Columns(0).Width = 80

        AddHandler defaultSpeeds.CheckedChanged, AddressOf defaultSpeeds_OnCheckedChanged
        defaultSpeeds.Checked = True
        speedsPage.Controls.Add(preHeatingLabel)
        speedsPage.Controls.Add(preHeatingText)
        speedsPage.Controls.Add(defaultSpeeds)
        speedsPage.Controls.Add(speedsGrid)
    End Sub

    Private Sub defaultSpeeds_OnCheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
        If defaultSpeeds.Checked = True Then
            Dim speeds() As Integer = {1800, 2000, 2400, 3000, 4000, 6000, 8000, 12000, 15000, 18000}
            For i As Integer = 0 To 9 Step 1
                speedsGrid.Rows(i).Cells(1).Value = speeds(i)
            Next
            speedsGrid.Columns(1).ReadOnly = True
        Else
            For i As Integer = 0 To 9 Step 1
                speedsGrid.Rows(i).Cells(1).Value = ""
            Next
            speedsGrid.Columns(1).ReadOnly = False
        End If
    End Sub

    Private Sub executeButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
        Select Case checkInputData()
            Case 0
                displayResults()
            Case 1
                MsgBox("Add at least one test case", vbCritical)
            Case 2
                MsgBox("I_CP is empty", vbCritical)
                I_CP.Focus()
            Case 3
                MsgBox("Choose at least one objectif", vbCritical)
                contextTab.SelectedTab = objectivesPage
            Case 4
                MsgBox("Every speed can be empty", vbCritical)
                speedsGrid.Focus()
            Case 5
                MsgBox("All speed must be different", vbCritical)
        End Select

    End Sub

    Private Function checkInputData() As Integer
        ' Check test case
        If testCasesTab Is Nothing Then
            Return 1
        Else
            Dim text1 As Control = testCasesTab.TabPages(0).Controls.Find("temperatureText", True)(0)
            Dim text2 As Control = testCasesTab.TabPages(0).Controls.Find("VdcText", True)(0)
            If text1.Text = "" And text2.Text = "" Then
                Return 1
            End If
        End If

        ' Check I_CP field
        If CP_check.Checked = True And I_CP.Text = "" Then
            Return 2
        End If

        ' Count checked objectives 
        Dim count As Integer = 0
        For i As Integer = 0 To 12
            If checkListBox.GetItemChecked(i) = True Then
                count += 1
            End If
        Next
        If count = 0 Then
            Return 3
        End If

        ' Check speeds
        If defaultSpeeds.Checked = False Then
            For i As Integer = 0 To 9
                For j As Integer = i + 1 To 9
                    If speedsGrid.Rows(i).Cells(1).Value = speedsGrid.Rows(j).Cells(1).Value Then
                        Return 5
                    End If
                Next
                If speedsGrid.Rows(i).Cells(1).Value = "" Then
                    Return 4
                End If
            Next
        End If

        Return 0
    End Function

    Private Sub I_CP_OnLeave(ByVal sender As Object, ByVal e As EventArgs)
        If Not IsNumeric(I_CP.Text) Then
            MsgBox("I_CP must have a numeric value", vbCritical)
            I_CP.Focus()
        End If
    End Sub

    Private Sub displayResults()
        Dim excelApp As Excel.Application
        Dim excelBook As Workbook
        Dim fileName As String = "e:\documents and settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\calcul\DEBIT_tri_TG11.xls"
        excelApp = New Excel.Application

        excelBook = excelApp.Workbooks.Open(fileName, Password:="aquarious")
        If excelBook.HasPassword = False Then
            excelBook.Password = "aquarious"
        End If
        excelBook.ReadOnlyRecommended = False
        exportButton.Enabled = True

        ' Create table Page
        resultsTab.Size = resultPage.Size
        resultsTab.TabPages.Clear()
        resultPage.Controls.Add(resultsTab)
        AddHandler resultsTab.SizeChanged, AddressOf resultsTab_OnSizeChanged
        createTablePage(excelBook)
        createGraphPage(excelBook)
        CreateVDAEfficiencyPage(excelBook)
        createGMNAEfficiencyPage(excelBook)


        excelBook.Close(True)
        excelApp.Quit()
    End Sub

    Private Sub createTablePage(ByRef excelBook As Workbook)
        Dim testCondition As Integer
        resultsTab.TabPages.Clear()
        tablePage.Controls.Clear()
        If CP_check.Checked = True Then
            testCondition = 2
        Else
            testCondition = 1
        End If
        Dim environ As Integer
        If coldCheck.Checked = True Then
            environ = 2
        Else
            environ = 1
        End If
        ' Create object calcul
        Dim calcul As New Calcul(combo.Text, testCondition, environ)

        ' Write Alter Infos
        Dim workSheet As Worksheet = excelBook.Worksheets("Feuille")
        calcul.writeAlter(workSheet)

        ' Write speeds
        Dim speeds() As Double = buildSpeedsTest()
        calcul.setSpeed(speeds)
        Dim sheetDebit As Worksheet = excelBook.Worksheets("Debit")
        calcul.writeSpeeds(sheetDebit)
        If preHeatingText.Text <> "" Then
            calcul.setPreHeatingSpeed(Double.Parse(preHeatingText.Text))
        Else
            calcul.setPreHeatingSpeed(5000)
        End If

        ' Write Material
        Dim material As Worksheet = excelBook.Worksheets("Material")
        calcul.writeMaterial(material)

        ' Write Thermal Coefficient
        Dim thermal As Worksheet = excelBook.Worksheets("Thermal input")
        calcul.writeThermal(thermal)

        If I_CP.Visible = True Then
            calcul.setICP(I_CP.Text)
        End If
        Dim numberTest As Integer = testCasesTab.TabPages.Count
        For i As Integer = 1 To numberTest
            Dim temperature As String = testCasesTab.TabPages(i - 1).Controls.Find("temperatureText", True)(0).Text
            Dim Vdc As String = testCasesTab.TabPages(i - 1).Controls.Find("VdcText", True)(0).Text
            calcul.setAmbientTemperature(Double.Parse(temperature))
            calcul.setVdc(Double.Parse(Vdc))
            Dim sheetOutput As Worksheet = excelBook.Worksheets("Output")
            calcul.writeGeneralInfo(sheetOutput)
            preLoadGraphes(sheetOutput, i)
            ' in CP test we wait 5 sec for the convergence
            'If I_CP.Visible Then
            '    System.Threading.Thread.Sleep(5000)
            'End If
            addTables(tablePage, i, sheetOutput)
        Next

        tablePage.Text = "Objectives"
        resultsTab.TabPages.Add(tablePage)
    End Sub

    Private Function buildSpeedsTest() As Object
        Dim speeds(0 To 9) As Double
        For i As Integer = 0 To 9
            speeds(i) = speedsGrid.Rows(i).Cells(1).Value
        Next
        Return speeds
    End Function

    Private Sub addTables(ByRef tablePage As TabPage, ByVal index As Integer, ByVal sheet As Worksheet)
        Dim grid As New System.Windows.Forms.DataGridView
        grid.Name = index
        grid.RowCount = 12
        grid.ColumnCount = checkListBox.CheckedItems.Count
        grid.AllowUserToAddRows = False
        grid.AllowUserToDeleteRows = False
        grid.AllowUserToOrderColumns = False
        grid.AllowUserToResizeColumns = False
        grid.AllowUserToResizeRows = False
        grid.ColumnHeadersHeight = 40
        grid.Width = 60 * grid.ColumnCount + 3
        grid.Height = grid.Rows(1).Height * 13
        Dim j As Integer = 0

        If index = 1 Then ' add a speed column
            grid.ColumnCount += 1
            j = 1
            grid.Columns(0).HeaderText = "Speeds"
            grid.Columns(0).Width = 60
            grid.Width += 60
            For i As Integer = 0 To 9
                grid.Rows(i + 1).Cells(0).Value = speedsGrid.Rows(i).Cells(1).Value
            Next
        Else
            grid.Location = New System.Drawing.Point(grid.Width * (index - 1) + 60, 0)
        End If

        For i As Integer = 0 To 12 ' (objectives)
            If checkListBox.GetItemChecked(i) = True Then
                grid.Columns(j).HeaderText = checkListBox.Items(i)
                grid.Columns(j).Width = 60
                j += 1
            End If
        Next
        Dim temperature As String = testCasesTab.TabPages(index - 1).Controls.Find("temperatureText", True)(0).Text
        Dim Vdc As String = testCasesTab.TabPages(index - 1).Controls.Find("VdcText", True)(0).Text
        grid.Rows(0).Cells(0).Value = "T° = " & temperature
        grid.Rows(0).Cells(1).Value = "Vdc = " & Vdc

        Dim defaultColumns() As String = {"C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"}
        Dim checkedColumns(0 To 12) As String
        Dim k As Integer = 0
        For i As Integer = 0 To 12 ' objectives

            If checkListBox.GetItemChecked(i) = True Then
                checkedColumns(k) = defaultColumns(i)
                k += 1
            End If
        Next
        Dim pos As Integer
        For i As Integer = 0 To k - 1
            For l As Integer = 1 To 10
                pos = 14 + l
                If index = 1 Then
                    If checkedColumns(i) = "F" Then ' display efficiency in %
                        grid.Rows(l).Cells(i + 1).Value = Math.Round(sheet.Range(checkedColumns(i) & pos).Value, 2) * 100
                    Else
                        grid.Rows(l).Cells(i + 1).Value = Math.Round(sheet.Range(checkedColumns(i) & pos).Value, 2)
                    End If
                Else
                    If checkedColumns(i) = "F" Then ' display efficiency in %
                        grid.Rows(l).Cells(i).Value = Math.Round(sheet.Range(checkedColumns(i) & pos).Value, 2) * 100
                    Else
                        grid.Rows(l).Cells(i).Value = Math.Round(sheet.Range(checkedColumns(i) & pos).Value, 2)
                    End If
                End If
            Next
        Next


        grid.RowHeadersVisible = False
        tablePage.Controls.Add(grid)
    End Sub

    Private Sub createGraphPage(ByVal excelBook As Workbook)
        graphPage.Text = "Graphes"
        graphPage.Controls.Clear()

        ' preload all graphes
        Dim outputSheet As Worksheet = excelBook.Worksheets("Output")
        'preLoadGraphes(outputSheet)

        Dim typesZone As New System.Windows.Forms.GroupBox
        typesZone.Text = "Types of graph :"
        typesZone.Name = "type"
        typesZone.Location = New System.Drawing.Point(10, 10)
        typesZone.Width = resultsTab.Width - 50
        typesZone.Height = resultsTab.Height / 7

        Dim outputCurrentGraph As New System.Windows.Forms.RadioButton
        outputCurrentGraph.Text = "Output Current"
        outputCurrentGraph.Name = "OutputCurrent"
        outputCurrentGraph.Location = New System.Drawing.Point(20, 20)
        typesZone.Controls.Add(outputCurrentGraph)

        Dim efficiencyGraph As New System.Windows.Forms.RadioButton
        efficiencyGraph.Text = "Efficiency"
        efficiencyGraph.Name = "Efficiency"
        efficiencyGraph.Location = New System.Drawing.Point(outputCurrentGraph.Right + 10, 20)
        typesZone.Controls.Add(efficiencyGraph)

        Dim fluxGraph As New System.Windows.Forms.RadioButton
        fluxGraph.Text = "Max Simple Flux"
        fluxGraph.Name = "MaxSimpleFlux"
        fluxGraph.Width = 150
        fluxGraph.Location = New System.Drawing.Point(efficiencyGraph.Right + 10, 20)
        typesZone.Controls.Add(fluxGraph)

        Dim torqueGraph As New System.Windows.Forms.RadioButton
        torqueGraph.Text = "Torque"
        torqueGraph.Name = "Torque"
        torqueGraph.Location = New System.Drawing.Point(fluxGraph.Right + 10, 20)
        typesZone.Controls.Add(torqueGraph)

        Dim TStatorGraph As New System.Windows.Forms.RadioButton
        TStatorGraph.Text = "T_Stator"
        TStatorGraph.Name = "T_Stator"
        TStatorGraph.Location = New System.Drawing.Point(torqueGraph.Right + 10, 20)
        typesZone.Controls.Add(TStatorGraph)

        Dim displayTab As New System.Windows.Forms.TabControl
        displayTab.Name = "displayTab"
        displayTab.Location = New System.Drawing.Point(10, typesZone.Bottom)
        displayTab.Size = New System.Drawing.Size(resultsTab.Width - 50, resultsTab.Height / 7 * 5)
        AddHandler displayTab.SelectedIndexChanged, AddressOf displayTab_OnSelectedIndexChanged
        For i As Integer = 0 To testCasesTab.TabCount - 1
            Dim displayZone As New System.Windows.Forms.TabPage
            displayZone.Text = "Case " & i + 1
            displayTab.TabPages.Add(displayZone)
            'AddHandler displayZone.SizeChanged, AddressOf displayZone_OnSizeChanged
        Next
        
        graphPage.Controls.Add(typesZone)
        graphPage.Controls.Add(displayTab)
        resultsTab.TabPages.Add(graphPage)

        AddHandler outputCurrentGraph.CheckedChanged, AddressOf outputCurrentGraph_OnCheckedchanged
        AddHandler efficiencyGraph.CheckedChanged, AddressOf efficiencyGraph_OnCheckedchanged
        AddHandler fluxGraph.CheckedChanged, AddressOf fluxGraph_OnCheckedchanged
        AddHandler torqueGraph.CheckedChanged, AddressOf torqueGraph_OnCheckedchanged
        AddHandler TStatorGraph.CheckedChanged, AddressOf TStatorGraph_OnCheckedchanged

        outputCurrentGraph.Checked = True
    End Sub

    Private Sub addGraph(ByVal name As String)
        Dim displayImage As New System.Windows.Forms.PictureBox
        displayImage.AutoSize = True
        displayImage.Dock = DockStyle.Fill
        displayImage.Name = "ImageBox"
        Dim location As String = "E:\Documents and Settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\images\"
        Dim displayTab As System.Windows.Forms.TabControl = graphPage.Controls.Find("displayTab", True)(0)
        Dim selectedTab As Integer = displayTab.SelectedIndex
        If selectedTab >= 0 Then
            Dim page As TabPage = displayTab.TabPages(selectedTab)
            page.Controls.Clear()
            displayImage.ImageLocation = location & "\test_" & selectedTab + 1 & "_chart_" & name & ".jpg"
            page.Controls.Add(displayImage)
        End If
    End Sub

    Private Sub preLoadGraphes(ByVal outputSheet As Worksheet, ByVal index As Integer)
        Dim c As Excel.Chart
        Dim location As String = "E:\Documents and Settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\images\"
        For i As Integer = 1 To 100
            Try
                c = outputSheet.ChartObjects(i).chart
                c.Export(location & "\test_" & index & "_chart_" & i & ".jpg", "JPEG", False)
            Catch e As Exception
                Exit For
            End Try
        Next
    End Sub

    Private Sub outputCurrentGraph_OnCheckedchanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim zone As Control = graphPage.Controls.Find("type", True)(0)
        Dim check As System.Windows.Forms.RadioButton = graphPage.Controls.Find("OutputCurrent", True)(0)
        If check.Checked Then
            addGraph("1")
        End If
    End Sub

    Private Sub efficiencyGraph_OnCheckedchanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim zone As Control = graphPage.Controls.Find("type", True)(0)
        Dim check As System.Windows.Forms.RadioButton = graphPage.Controls.Find("Efficiency", True)(0)
        If check.Checked Then
            addGraph("2")
        End If
    End Sub

    Private Sub fluxGraph_OnCheckedchanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim zone As Control = graphPage.Controls.Find("type", True)(0)
        Dim check As System.Windows.Forms.RadioButton = graphPage.Controls.Find("MaxSimpleFlux", True)(0)
        If check.Checked Then
            addGraph("3")
        End If
    End Sub

    Private Sub torqueGraph_OnCheckedchanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim zone As Control = graphPage.Controls.Find("type", True)(0)
        Dim check As System.Windows.Forms.RadioButton = graphPage.Controls.Find("Torque", True)(0)
        If check.Checked Then
            addGraph("4")
        End If
    End Sub

    Private Sub TStatorGraph_OnCheckedchanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim zone As Control = graphPage.Controls.Find("type", True)(0)
        Dim check As System.Windows.Forms.RadioButton = graphPage.Controls.Find("T_Stator", True)(0)
        If check.Checked Then
            addGraph("5")
        End If
    End Sub

    Private Sub resultPage_OnSizeChanged(ByVal sender As Object, ByVal e As EventArgs)
        resultsTab.Size = resultPage.Size
    End Sub

    Private Sub resultsTab_OnSizeChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim zone1 As Control = graphPage.Controls.Find("type", True)(0)
        Dim zone2 As Control = graphPage.Controls.Find("display", True)(0)
        If Not zone1 Is Nothing Then
            zone1.Width = resultsTab.Width - 50
            zone1.Height = resultsTab.Height / 7
        End If
        If Not zone2 Is Nothing Then
            zone2.Location = New System.Drawing.Point(10, zone1.Bottom)
            zone2.Width = resultsTab.Width - 50
            zone2.Height = (resultsTab.Height / 7) * 5.5 - 10
        End If
    End Sub

    Private Sub CreateVDAEfficiencyPage(ByVal excelBook As Workbook)
        VDACalculePage.Text = "VDA Efficiency : "
        VDACalculePage.Controls.Clear()
        Dim sheetDebit As Worksheet = excelBook.Worksheets("Debit")
        Dim sheetOutput As Worksheet = excelBook.Worksheets("Output")
        Dim descriptionZone As New System.Windows.Forms.GroupBox
        descriptionZone.Text = "Description : "
        descriptionZone.Name = "Description"
        descriptionZone.Location = New System.Drawing.Point(20, 20)
        descriptionZone.Width = resultPage.Width - 50
        descriptionZone.Height = resultPage.Height / 7 * 1.5
        Dim text As New System.Windows.Forms.Label
        text.Text = "VDA Eficciency according to GMW14036 3.2.7.1" & vbCrLf & _
                    "N(VDA) = (0.25*N(1800)) + ( 0.4 * N(3000))+(0.25*N(6000))+(0.1*N(10000)) " & vbCrLf & _
                    "50% of the rated current obtained at a speed of 6000 rpm." & vbCrLf & _
                    "I(6000) 50%"
        Dim calcul As New Calcul(combo.Text, 1, 2)
        calcul.setPreHeatingSpeed(5000)
        Dim speeds() As Double = {1800, 2000, 2400, 3000, 4000, 6000, 8000, 10000, 15000, 18000}
        calcul.setSpeed(speeds)
        calcul.setAmbientTemperature(25)
        calcul.setVdc(14.3)
        calcul.writeSpeeds(sheetDebit)
        calcul.writeGeneralInfo(sheetOutput)
        'MsgBox(sheetOutput.Range("C19").Value)
        Dim A As Double = sheetOutput.Range("C20").Value / 2
        ' change the speeds
        speeds(1) = 3000
        speeds(2) = 6000
        speeds(3) = 10000
        calcul.setTestConditions(2)
        calcul.setICP(A)
        calcul.setSpeed(speeds)
        calcul.writeSpeeds(sheetDebit)
        calcul.writeGeneralInfo(sheetOutput)
        ' in CP test we wait 5 sec for the convergence
        'If I_CP.Visible Then
        '    System.Threading.Thread.Sleep(10000)
        'End If

        Dim tableZone As New System.Windows.Forms.GroupBox
        tableZone.Text = "Result : In stabilized temperature at 25°"
        tableZone.Name = "VDAResultTableZone"
        tableZone.Location = New System.Drawing.Point(20, descriptionZone.Bottom)
        tableZone.Size = New System.Drawing.Size(resultPage.Width - 50, resultPage.Height / 7 * 2)

        VDAGrid.Name = "VDAGrid"
        VDAGrid.ColumnCount = 5
        VDAGrid.RowCount = 5
        VDAGrid.Columns(0).HeaderText = "Speed (rpm)"
        VDAGrid.Columns(1).HeaderText = "I (A)"
        VDAGrid.Columns(2).HeaderText = "UB + (V)"
        VDAGrid.Columns(3).HeaderText = "Torque (N.m)"
        VDAGrid.Columns(4).HeaderText = "Efficiency (%)"
        VDAGrid.AutoSize = True
        VDAGrid.Dock = DockStyle.Fill

        ' import results
        Dim base As Integer = 15
        For i As Integer = 0 To 3
            VDAGrid.Rows(i).Cells(0).Value = speeds(i)
            VDAGrid.Rows(i).Cells(1).Value = Math.Round(A * 2, 2)
            VDAGrid.Rows(i).Cells(2).Value = "14,3"
            VDAGrid.Rows(i).Cells(3).Value = Math.Round(sheetOutput.Range("D" & base + i).Value, 2)
            VDAGrid.Rows(i).Cells(4).Value = Math.Round(sheetOutput.Range("F" & base + i).Value * 100, 2)
        Next
        VDAGrid.Rows(4).Cells(3).Value = "VDA : "
        VDAGrid.Rows(4).Cells(4).Value = Math.Round(0.25 * VDAGrid.Rows(0).Cells(4).Value + _
                                         0.4 * VDAGrid.Rows(1).Cells(4).Value + _
                                         0.25 * VDAGrid.Rows(2).Cells(4).Value + _
                                         0.1 * VDAGrid.Rows(3).Cells(4).Value, 2)

        text.AutoSize = True
        text.Dock = DockStyle.Fill
        descriptionZone.Controls.Add(text)
        VDACalculePage.Controls.Add(descriptionZone)
        VDACalculePage.Controls.Add(tableZone)
        tableZone.Controls.Add(VDAGrid)
        resultsTab.TabPages.Add(VDACalculePage)
    End Sub

    Private Sub createGMNAEfficiencyPage(ByVal excelBook As Workbook)
        GMNACalculePage.Text = "GMNA Efficiency : "
        GMNACalculePage.Controls.Clear()
        Dim sheetDebit As Worksheet = excelBook.Worksheets("Debit")
        Dim sheetOutput As Worksheet = excelBook.Worksheets("Output")
        Dim descriptionZone As New System.Windows.Forms.GroupBox
        descriptionZone.Text = "Description : "
        descriptionZone.Name = "Description"
        descriptionZone.Location = New System.Drawing.Point(20, 20)
        descriptionZone.Width = resultPage.Width - 50
        descriptionZone.Height = resultPage.Height / 7 * 1.5
        Dim text As New System.Windows.Forms.Label
        text.Text = "GMNA Efficiency according to GMW14036 3.2.7.2 " & vbCrLf & _
                    "N(GMNA) = (0.2*N(2000)) + ( 0.1 * N(3000))+(0.3*N(4000))+(0.3*N(5000))+(0.1*N(6500)) " & vbCrLf & _
                    "25A of load at 12.8 V" & vbCrLf

        Dim calcul As New Calcul(combo.Text, 2, 2)
        calcul.setPreHeatingSpeed(5000)
        Dim speeds() As Double = {2000, 3000, 4000, 5000, 6500, 6500, 8000, 10000, 15000, 18000}
        calcul.setSpeed(speeds)
        calcul.setAmbientTemperature(25)
        calcul.setVdc(12.8)
        calcul.writeSpeeds(sheetDebit)
        calcul.setICP(25)
        calcul.writeGeneralInfo(sheetOutput)

        Dim tableZone As New System.Windows.Forms.GroupBox
        tableZone.Text = "Result : In stabilized temperature at 25°"
        tableZone.Name = "VDAResultTableZone"
        tableZone.Location = New System.Drawing.Point(20, descriptionZone.Bottom)
        tableZone.Size = New System.Drawing.Size(resultPage.Width - 50, resultPage.Height / 7 * 2)

        GMNAGrid.Name = "GMNAGrid"
        GMNAGrid.ColumnCount = 5
        GMNAGrid.RowCount = 6
        GMNAGrid.Columns(0).HeaderText = "Speed (rpm)"
        GMNAGrid.Columns(1).HeaderText = "I (A)"
        GMNAGrid.Columns(2).HeaderText = "UB + (V)"
        GMNAGrid.Columns(3).HeaderText = "Torque (N.m)"
        GMNAGrid.Columns(4).HeaderText = "Efficiency (%)"
        GMNAGrid.AutoSize = True
        GMNAGrid.Dock = DockStyle.Fill

        ' import results
        Dim base As Integer = 15
        For i As Integer = 0 To 4
            GMNAGrid.Rows(i).Cells(0).Value = speeds(i)
            GMNAGrid.Rows(i).Cells(1).Value = "25"
            GMNAGrid.Rows(i).Cells(2).Value = "12,8"
            GMNAGrid.Rows(i).Cells(3).Value = Math.Round(sheetOutput.Range("D" & base + i).Value, 2)
            GMNAGrid.Rows(i).Cells(4).Value = Math.Round(sheetOutput.Range("F" & base + i).Value * 100, 2)
        Next
        GMNAGrid.Rows(5).Cells(3).Value = "GMNA : "
        GMNAGrid.Rows(5).Cells(4).Value = Math.Round(0.2 * GMNAGrid.Rows(0).Cells(4).Value + _
                                         0.1 * GMNAGrid.Rows(1).Cells(4).Value + _
                                         0.3 * GMNAGrid.Rows(2).Cells(4).Value + _
                                         0.3 * GMNAGrid.Rows(3).Cells(4).Value + _
                                         0.1 * GMNAGrid.Rows(4).Cells(4).Value, 2)

        text.AutoSize = True
        text.Dock = DockStyle.Fill
        descriptionZone.Controls.Add(text)
        GMNACalculePage.Controls.Add(descriptionZone)
        GMNACalculePage.Controls.Add(tableZone)
        tableZone.Controls.Add(GMNAGrid)
        resultsTab.TabPages.Add(GMNACalculePage)
    End Sub

    Private Sub displayTab_OnSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim outputCheck As System.Windows.Forms.RadioButton = graphPage.Controls.Find("OutputCurrent", True)(0)
        outputCheck.Checked = True
    End Sub

    Private Sub torqueMapButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
        ' add new tab page for this map
        If mainForm.rightTabControl.TabPages.Contains(torqueMapPage) = False Then
            torqueMapPage.Text = "Torque and Efficiency Map"
            mainForm.rightTabControl.SelectedTab = torqueMapPage
            mainForm.rightTabControl.TabPages.Add(torqueMapPage)
        End If

        ' add new tab control
        torqueTab.Size = resultsTab.Size
        torqueMapPage.Controls.Add(torqueTab)

        Dim torquePage As New System.Windows.Forms.TabPage
        torquePage.Text = "Torque (N.m)"
        torqueTab.TabPages.Add(torquePage)

        Dim effiPage As New System.Windows.Forms.TabPage
        effiPage.Text = "Efficiency (%)"
        torqueTab.TabPages.Add(effiPage)

        Dim excelApp As Excel.Application
        Dim excelBook As Workbook
        Dim fileName As String = "e:\documents and settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\calcul\DEBIT_tri_TG11.xls"
        excelApp = New Excel.Application
        excelBook = excelApp.Workbooks.Open(fileName, Password:="aquarious")
        If excelBook.HasPassword = False Then
            excelBook.Password = "aquarious"
        End If
        Dim debitSheet As Worksheet = excelBook.Worksheets("Debit")
        Dim inputSheet As Worksheet = excelBook.Worksheets("Feuille")
        Dim outputSheet As Worksheet = excelBook.Worksheets("Output")
        Dim icp As Double = 0
        Dim calcul As New Calcul(combo.Text, 2, 2)
        calcul.writeAlter(inputSheet)
        Dim speeds() As Double = {1300, 1325, 1350, 1375, 1400, 1425, 1450, 1475, 1500, 1525, 1550, 1575, 1600, 1750, 2000, 2500, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000}
        calcul.setSpeed(speeds)
        calcul.writeSpeeds(debitSheet)
        calcul.setPreHeatingSpeed(5000)
        calcul.setAmbientTemperature(25)
        calcul.setVdc(14)

        Dim torqueGrid As New System.Windows.Forms.DataGridView
        Dim effGrid As New System.Windows.Forms.DataGridView
        torqueGrid.Name = "torqueGrid"
        effGrid.Name = "effGrid"
        torqueGrid.AutoSize = True
        torqueGrid.Dock = DockStyle.Fill
        torqueGrid.RowCount = 26
        torqueGrid.ColumnCount = 21
        effGrid.RowCount = 26
        effGrid.ColumnCount = 21
        effGrid.AutoSize = True
        effGrid.Dock = DockStyle.Fill
        effGrid.RowCount = 26
        torqueGrid.RowHeadersVisible = False
        effGrid.RowHeadersVisible = False

        For i As Integer = 1 To speeds.Length
            torqueGrid.Rows(i - 1).Cells(0).Value = speeds(i - 1)
            effGrid.Rows(i - 1).Cells(0).Value = speeds(i - 1)
        Next


        For i As Integer = 0 To 19
            calcul.setICP(icp)
            calcul.writeGeneralInfo(outputSheet)
            For j As Integer = 0 To 125
                excelApp.Calculate()
            Next
            createTwoGrid(debitSheet, icp, torqueGrid, effGrid)
            icp += 10
        Next
        torquePage.Controls.Add(torqueGrid)
        effiPage.Controls.Add(effGrid)
        excelBook.Close(True)
        excelApp.Quit()
    End Sub

    Private Sub exportButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
        ' Open form file
        Dim formPath As String = "e:\documents and settings\tle\My Documents\Visual Studio 2010\Projects\IHM Alter\IHM Alter\export\exportReportForm.xls"
        Dim exApp As New Excel.Application
        Dim exBook As Workbook = exApp.Workbooks.Open(formPath)

        ' Save report file
        Dim saveBox As New System.Windows.Forms.SaveFileDialog
        saveBox.Filter = "Excel WorkSheet|*.xls"
        saveBox.ShowDialog()
        If saveBox.FileName <> "" Then
            addReportTitle(exBook)
            addFullLoadResults(exBook)
            addEfficiencyResults(exBook)
            addTorqueMap(exBook)
            Try
                exBook.SaveAs(saveBox.FileName)
            Catch ex As Exception
            End Try
        End If
        exBook.Close()
        exApp.Quit()
    End Sub

    Private Sub closeButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
        parameterPage.Dispose()
        resultPage.Dispose()
        torqueMapPage.Dispose()
    End Sub

    Private Sub createTwoGrid(ByVal debitSheet As Worksheet, ByVal icp As Double, ByRef torqueGrid As DataGridView, ByRef effGrid As DataGridView)
        Dim column As Integer = (icp / 10) + 1
        torqueGrid.Columns(column).HeaderText = icp
        effGrid.Columns(column).HeaderText = icp
        Dim baseOutput As Integer = 19
        Dim baseTorque As Integer = 196
        For i As Integer = 0 To 23
            If Math.Abs(debitSheet.Range("D" & baseOutput + i).Value - icp) < 0.01 Then
                torqueGrid.Rows(i).Cells(column).Value = Math.Round(debitSheet.Range("AI" & baseTorque + i).Value, 2)
                effGrid.Rows(i).Cells(column).Value = Math.Round(debitSheet.Range("AG" & baseTorque + i).Value, 2) * 100
            End If
        Next
    End Sub

    Private Sub addReportTitle(ByRef exBook As Workbook)
        Dim titlePage As Worksheet = exBook.Worksheets("Title page")
        titlePage.Range("D3").Value = combo.Text & "- Output Current Torque and efficiency map"

        Dim objectivePage As Worksheet = exBook.Worksheets("Objectives & Context")
        objectivePage.Range("D3").Value = combo.Text & "- Output Current Torque and efficiency map"
        objectivePage.Range("D4").Value = "Objectives and main conclusion"

        Dim outPutFullLoadPage As Worksheet = exBook.Worksheets("1. Output Full load")
        outPutFullLoadPage.Range("D3").Value = combo.Text & "- Output Current Torque and efficiency map"
        outPutFullLoadPage.Range("D4").Value = "Results"

        Dim VDAPage As Worksheet = exBook.Worksheets("2. VDA Efficiency")
        VDAPage.Range("D3").Value = combo.Text & "- VDA Efficiency"
        VDAPage.Range("D4").Value = "Results"

        Dim GMNAPage As Worksheet = exBook.Worksheets("3. GMNA Efficiency")
        GMNAPage.Range("D3").Value = combo.Text & "- GMNA Efficiency"
        GMNAPage.Range("D4").Value = "Results"

        Dim mapPage As Worksheet = exBook.Worksheets("4. Torque & Eff. Map 14V")
        mapPage.Range("D3").Value = combo.Text & "- Torque and Efficiency Map - 14V"
        mapPage.Range("D4").Value = "Results"
    End Sub

    Private Sub addFullLoadResults(ByVal exBook As Workbook)
        Dim titlePage As Worksheet = exBook.Worksheets("Title page")
        Dim user As User = mainForm.currentUser
        titlePage.Range("C17").Value = user.getFirstName & " " & user.getLastName
        titlePage.Range("C18").Value = Today
        titlePage.Range("B31").Value = user.getFirstName & " " & user.getLastName
        titlePage.Range("F31").Value = user.getFunctionCompany
        titlePage.Range("D38").Value = Today
        titlePage.Range("E38").Value = user.getFirstName & " " & user.getLastName

        Dim objectivePage As Worksheet = exBook.Worksheets("Objectives & Context")
        objectivePage.Range("C11").Value = combo.Text
        objectivePage.Range("B18").Value = "1.- Output current, Torque and efficiency @ lower speed, "
        Dim outPutFullLoadPage As Worksheet = exBook.Worksheets("1. Output Full load")
        outPutFullLoadPage.Range("B9").Value = "1.- Output current, Torque and efficiency @ lower speed, "
        Dim base As Integer = 19
        Dim indexObjectKey = 0
        Dim objectivesKey() As String = {"C", "D", "E", "F", "G", "H", "I", "J", "K"}
        For i As Integer = 0 To testCasesTab.TabCount - 1
            Dim ambientText As System.Windows.Forms.TextBox = testCasesTab.TabPages(i).Controls.Find("temperatureText", True)(0)
            Dim VdcText As System.Windows.Forms.TextBox = testCasesTab.TabPages(i).Controls.Find("VdcText", True)(0)
            If i = testCasesTab.TabCount - 1 Then
                objectivePage.Range("B18").Value = objectivePage.Range("B18").Value & ambientText.Text & "."
                outPutFullLoadPage.Range("B9").Value = outPutFullLoadPage.Range("B9").Value & ambientText.Text & "."
            Else
                objectivePage.Range("B18").Value = objectivePage.Range("B18").Value & ambientText.Text & " / "
                outPutFullLoadPage.Range("B9").Value = outPutFullLoadPage.Range("B9").Value & ambientText.Text & " / "
            End If

            objectivePage.Range("C" & base).Value = ambientText.Text & "°C   @  " & VdcText.Text & "V"
            outPutFullLoadPage.Range("C" & base - 9).Value = ambientText.Text & "°C   @  " & VdcText.Text & "V"
            If i = 0 Then
                outPutFullLoadPage.Range("C18").Value = "AT STABILIZED " & ambientText.Text & "DEG " & VdcText.Text & "V"
            ElseIf i = 1 Then
                outPutFullLoadPage.Range("F18").Value = "AT STABILIZED " & ambientText.Text & "DEG " & VdcText.Text & "V"
            Else
                outPutFullLoadPage.Range("I18").Value = "AT STABILIZED " & ambientText.Text & "DEG " & VdcText.Text & "V"
            End If
            base += 1
            Dim grid As System.Windows.Forms.DataGridView = tablePage.Controls.Find(i + 1, True)(0)
            For k As Integer = 0 To 2
                If i = 0 Then
                    outPutFullLoadPage.Range(objectivesKey(indexObjectKey) & "19").Value = grid.Columns(k + 1).HeaderText
                Else
                    outPutFullLoadPage.Range(objectivesKey(indexObjectKey) & "19").Value = grid.Columns(k).HeaderText
                End If
                indexObjectKey += 1
            Next
            Dim baseGrid As Integer = 20
            For p As Integer = 1 To speedsGrid.RowCount - 1
                For q As Integer = 3 * i To 3 * (i + 1) - 1
                    If i = 0 Then
                        If grid.Columns((q Mod 3) + 1).HeaderText = "Efficiency" Then
                            outPutFullLoadPage.Range(objectivesKey(q) & baseGrid).Value = grid.Rows(p).Cells((q Mod 3) + 1).Value / 100
                        Else
                            outPutFullLoadPage.Range(objectivesKey(q) & baseGrid).Value = grid.Rows(p).Cells((q Mod 3) + 1).Value
                        End If
                    Else
                        If grid.Columns(q Mod 3).HeaderText = "Efficiency" Then
                            outPutFullLoadPage.Range(objectivesKey(q) & baseGrid).Value = grid.Rows(p).Cells(q Mod 3).Value / 100
                        Else
                            outPutFullLoadPage.Range(objectivesKey(q) & baseGrid).Value = grid.Rows(p).Cells(q Mod 3).Value
                        End If
                    End If
                Next
                baseGrid += 1
            Next
        Next

        base = 20
        For i As Integer = 0 To speedsGrid.RowCount - 1
            objectivePage.Range("B22").Value = objectivePage.Range("B22").Value & speedsGrid.Rows(i).Cells(1).Value & "rpm / "
            outPutFullLoadPage.Range("B13").Value = outPutFullLoadPage.Range("B13").Value & speedsGrid.Rows(i).Cells(1).Value & "rpm / "
            outPutFullLoadPage.Range("B" & base).Value = speedsGrid.Rows(i).Cells(1).Value
            base += 1
        Next

    End Sub

    Private Sub addEfficiencyResults(ByVal exBook As Workbook)
        Dim VDAPage As Worksheet = exBook.Worksheets("2. VDA Efficiency")
        Dim key() As String = {"C", "", "E", "F"}
        Dim base As Integer = 16
        For i As Integer = 0 To 4
            For j As Integer = 0 To 3
                If key(j) <> "" Then
                    If j = 3 Then
                        VDAPage.Range(key(j) & base).Value = VDAGrid.Rows(i).Cells(j + 1).Value / 100
                    Else
                        VDAPage.Range(key(j) & base).Value = VDAGrid.Rows(i).Cells(j + 1).Value
                    End If
                End If
            Next
            base += 1
        Next

        Dim GMNAPage As Worksheet = exBook.Worksheets("3. GMNA Efficiency")
        base = 14
        For i As Integer = 0 To 4
            For j As Integer = 2 To 3
                If j = 3 Then
                    GMNAPage.Range(key(j) & base).Value = GMNAGrid.Rows(i).Cells(j + 1).Value / 100
                Else
                    GMNAPage.Range(key(j) & base).Value = GMNAGrid.Rows(i).Cells(j + 1).Value
                End If
            Next
            base += 1
        Next
    End Sub

    Private Sub addTorqueMap(ByVal exBook As Workbook)
        If torqueTab.TabPages.Count > 0 Then
            Dim mapPage As Worksheet = exBook.Worksheets("4. Torque & Eff. Map 14V")
            Dim torqueGrid As System.Windows.Forms.DataGridView = torqueTab.TabPages(0).Controls.Find("torqueGrid", True)(0)
            Dim effGrid As System.Windows.Forms.DataGridView = torqueTab.TabPages(1).Controls.Find("effGrid", True)(0)
            Dim baseTorque As Integer = 18
            Dim baseEff As Integer = 45
            Dim key() As String = {"C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V"}
            For i As Integer = 0 To 23
                For j As Integer = 0 To 19
                    mapPage.Range(key(j) & baseTorque).Value = torqueGrid.Rows(i).Cells(j + 1).Value
                    If Not effGrid.Rows(i).Cells(j + 1).Value Is Nothing Then
                        mapPage.Range(key(j) & baseEff).Value = effGrid.Rows(i).Cells(j + 1).Value / 100
                    End If
                Next
                baseTorque += 1
                baseEff += 1
            Next
        End If
    End Sub

End Class

Public Class ProgressForm
    Private form As System.Windows.Forms.Form
    Private progressBar As System.Windows.Forms.ProgressBar
    Private sec As Double
    Private partis As Double
    Sub New(ByVal text As String, ByVal _sec As Double, ByVal partis As Double)
        form = New Form
        form.Width = 300
        form.Height = 100
        form.StartPosition = FormStartPosition.CenterScreen
        form.Text = text
        form.ControlBox = False

        progressBar = New System.Windows.Forms.ProgressBar
        progressBar.Location = New System.Drawing.Point(20, 20)
        progressBar.Style = ProgressBarStyle.Continuous
        progressBar.Minimum = 0
        progressBar.Maximum = 100
        progressBar.Value = 1
        progressBar.Step = 100 / partis
        progressBar.Width = 250
        form.Controls.Add(progressBar)
        progressBar.Visible = True
        form.Controls.Add(progressBar)
        sec = _sec
        Me.partis = partis
        form.Show()
    End Sub

    Public Sub run()
        progressBar.PerformStep()
        System.Threading.Thread.Sleep(sec * 10)
    End Sub
    Public Sub destroy()
        form.Close()
    End Sub
End Class


